define(['moment', 'sortablejs'], function (moment, Sortable) {
        return ['$scope', '$filter', '$stateParams', '$mdDialog', 'config', 'MMWService', '$calculater', '$datePicker', '$timeout', "$state",'$compile','$rootScope',"customOrderService",
                function ($scope, $filter, $stateParams, $mdDialog, config, $MMWService, $calculater, $datePicker, $timeout, $state,$compile,$rootScope,customOrderService) {
                        // 20230911 modify by Alan for #136071: 增加跨頁選中功能
                        // 已選待派暫存
                        let dispatch_detail_checked = [];

                        $scope.Mode = '';
                        $scope.machineList = [];//區域內的機台列表
                        $scope.machine_detail = [];
                        $scope.plot_no = "";
                        $scope.PageConfig = { page: 0, page_count: 25 };
                        $scope.dispatch_filter = {};
                        $scope.is_lock_sort = false;
                        $scope.select_all_bool = false;
                        $scope.roll_back_all_bool = false;
                        $scope.order_by_mode = { name: "", sort: false };
                        $scope.assigned_machine = ''; // 過濾已派工的設備編號或設備名稱
                        $scope.acc_detail = [];
                        $scope.ht_tr_bool = false; //M#95547 add by a991241234 熱處理 是否顯示爐量
                        $scope.op_group_detail = [];
                        $scope.pluginType ="";//工艺类型
                        $scope.Switch = false;
                        let today = moment(new Date()).format('YYYY-MM-DD');
                        $scope.currentDate = today; // 今天
                        $scope.deviceListData = {}; // 设备列表详情
                        $scope.need_dispatch_plot_detail = [];
                        $scope.pageStyle = '';
                        var arr = [{name:"11"},{name:"11"}];
                      //  updateResult(arr);
                        $scope.data = [
                                { label: $filter('translate')('A08.all'), code: "0" },
                                { label: $filter('translate')('A08.enteredStation'), code: "1" },
                                { label: $filter('translate')('A08.upComplete'), code: "2" },
                                  
                              ]
                        $scope.initPlotNoStatus =  $scope.data[0].label;
                        $scope.project_status_code =  $scope.data[0].code;
                        function updateResult(item,items,param) {
                                let list = generateResultHeader(item,items);
                                if ($('.result-list').length != 0  && param ==1) {
                                        $('.result-list').html("");
                                        $('.result-list').append(list);
                                     
                                }else {
                                        $('.result-list').html("");
                                        $('.result-list').append(list);  
                                }
                               // $('.result-list').replaceWith(list);
                               $compile(list)($scope);
                        }
                       function generateResultHeader(item,items) {
                         let rows = generateResultRow(items);
                         let start = `<div class="kmi-list column-selector">
                                        <div class="kmi-list__header">
                                         <div class="kmi-list__column require" style="flex:0 0 80px;" ng-bind="'A05.equipment_view.equipment_no' | translate"></div>
                                         <div class="kmi-list__column require"  style="flex:1 0 130px;" ng-bind="'A03.list.column4' | translate"></div>
                                         <div class="kmi-list__column head-controls require"  style="flex:1 0 130px;">
                                         <div class="order"><label ng-bind="'A02.list.column3' | translate"></label></div>
                                         </div>
                                         <div class="kmi-list__column head-controls require" style="flex:1 0 120px;">
                                         <div class="order">
                                           <label ng-bind="'A02.list.column1' | translate"></label>
                                         </div>
                                         </div>                                   
                                         <div class="kmi-list__column head-controls require" style="flex:0 0 150px;">
                                            <div class="order">
                                                <label ng-bind="'A02.list.column2' | translate"></label>
                                            </div>
                                          </div>               
                                          <div class="kmi-list__column head-controls require" style="flex:1 0 80px;">
                                               <div class="order">
                                                   <label ng-bind="'A02.list.column5' | translate"></label>
                                               </div>
                                           </div>
                                           <div class="kmi-list__column head-controls require" style="flex:0 0 150px;">
                                               <div class="order">
                                                   <label ng-bind="'A02.list.column6' | translate"></label>
                                               </div>
                                            </div>
                                            <div class="kmi-list__column head-controls require" style="flex:0 0 40px;">
                                                 <div class="order">
                                                     <label ng-bind="'A08.edit' | translate"></label>
                                                 </div>
                                             </div>
                                             <div class="kmi-list__column head-controls require" style="flex:0 0 64px;">
                                                 <div class="order" >
                                                     <label ng-bind="'A08.undelivered_quantity' | translate"></label>
                                                 </div>
                                             </div>`;
                           let end = `</div>
                                        <div class="kmi-list__row-content">
                                          ${rows}
                                        </div>
                                    </div>`;
                        let columns = ''
                       
                        item.forEach(field => 
                            columns += `<div class="kmi-list__column" style="flex: 0 0 70px;" ng-bind="'${ field.work_date.split('-')[1] }' + '/' + '${ field.work_date.split('-')[2] }'"></div>`);
                        let list = $(start + columns + end);
        
                        return list
                    }
        
                    function generateResultRow(item) {
                        var row = '';
                        var columns = ``
                        var start = `<div class="kmi-list__row" ng-class="{'is-select': data.isSelect}" ng-repeat="data in main_event.list">
                                        <div class="kmi-list__column column-border" style="flex:0 0 100px;font-size: 14px;" ng-bind="data.machine_no"></div> 
                                        <div class="kmi-list__column column-border" style="flex:1 0 150px;font-size: 14px;" ng-bind="data.machine_name"></div> 
                                        <div class="kmi-list__column column-border" style="flex:1 0 150px;font-size: 14px;" ng-bind="data.plot_no"></div>
                                        <div class="kmi-list__column column-border" style="flex:0 0 100px;font-size: 14px;" ng-bind="data.op_no"></div>
                                        <div class="kmi-list__column column-border" style="flex:1 0 150px;font-size: 14px;" ng-bind="data.op_name"></div>
                                        <div class="kmi-list__column column-border" style="flex:0 0 100px;font-size: 14px;" ng-bind="data.product_no"></div>
                                        <div class="kmi-list__column column-border" style="flex:1 0 150px;font-size: 14px;" ng-bind="data.product_name"></div>
                                        <div class="kmi-list__column column-border" style="flex:1;height: 100%">
                                        <button class="mdl-button mdl-js-button mdl-button--icon" style="z-index:2" ng-click="detailRollback($index,data);">
                                           <img ng-show="data.checked!='Y'" src="image/icons/mould.png"></img>
                                           <img ng-show="data.checked=='Y'" src="image/icons/check1.png"></img>
                                        </button>
                                       </div>

                                       <div class="kmi-list__column column-input column-border" style="flex:0 0 64px;z-index:1;">
                                        <input type="text"  ng-value="data.undisqty"  ng-disabled="true">
                                        </div>    
                                        <div class="kmi-list__column column-input column-border" style="flex:1;z-index:1;min-width:50px" ng-repeat="flag in data.lst_ORM_PatchPeriodModel">
                                          <input type="text" οnfοcus="this.blur()" readonly="readonly" ng-click="dateSetDispatchVolume(data,flag,main_event.list);" ng-disabled="flag.disabled"  ng-value="flag.qty">
                                        </div> 
                                     
                                        `;
                        var end =   `   <div class="kmi-can-click" ng-click="main_event.select(data)"></div>
                                    </div>`;
                      
                        row = start + columns + end;
        
                        return row;
                    }
                      var MainPageEvent = function () {
                                return {
                                    headerTitle:
                                        $filter("translate")("QT07.prefix") +
                                        "｜" +
                                        $filter("translate")("QT07.title"),
                                    model_name: '',
                                    TDList: [],
                                    condition: [],
                                    DTList: $scope.list,
                                    columnList: [],
                                    list: $scope.list,
                              
                                    extendData: {
                                        columnList: [],
                                        data: []
                                    },
                                    resultPageConfig: {
                                        page: 0,
                                        page_count: 25,
                                    },
                                    extendPageConfig: {
                                        page: 0,
                                        page_count: 25,
                                    } ,
                                    async init() {            
                                
                                    },
                                    input_check_out_qty($event, data, $index) {
                                        dialog.input_check_out_qty($event, data, $index);
                                    }                      
                                  
                                };
                            };
                        $scope.conditions = {
                                pack_date_start: today,
                                pack_date_end: moment(today).add(6, 'd').format('YYYY-MM-DD'),
                                pack_user: '',

                        };
                        // 获取N天前日期
                        function getPrevDay(date, days) {
                                return new Date(date + days * 24 * 60 * 60 * 1000);
                        }


                        $scope.pageSetting = { PageNumber: 1, PageRow: 25, TotalPage: 1 };


                        $scope.equipment_sort_option_list =
                                [{ label: $filter('translate')('A02.equipment_sort_list.option_0'), code: "0" },
                                { label: $filter('translate')('A02.equipment_sort_list.option_1'), code: "1" },
                                { label: $filter('translate')('A02.equipment_sort_list.option_2'), code: "2" },
                                { label: $filter('translate')('A02.equipment_sort_list.option_3'), code: "3" },
                                { label: $filter('translate')('A02.equipment_sort_list.option_4'), code: "4" },
                                { label: $filter('translate')('A02.equipment_sort_list.option_5'), code: "5" },
                                { label: $filter('translate')('A02.equipment_sort_list.option_6'), code: "6" }
                               
                        ];

                        $scope.equipment_sort_mode_label = $scope.equipment_sort_option_list[0].label;
                        $scope.equipment_sort_mode = $scope.equipment_sort_option_list[0].code;
                        $scope.equipment_sort_mode_change = false;
                        $scope.product_detail = [];

                        // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
                        $scope.area_detail = [];
                        $scope.selectareaNo = "";
                        $scope.isLine = "";
                        $scope.selectWorkStation = '';
                        $scope.selectWorkStationName = '';
                        $scope.dispatch_detail = [];
                        // 实体分页查询功能实现 20221116 modify by shiwl  for M#18991
                        let targetData;
                      
                        $scope.blurSearch = function (e) {
                                var keycode = window.event ? e.keyCode : e.which;
                                if (keycode == 13) {
                                        $scope.pageSetting.PageNumber = 1;
                                        targetData = {
                                                qty: $scope.dispatch_filter.qty ? $scope.dispatch_filter.qty : 0,
                                                plot_start_time: $scope.dispatch_filter.plot_start_time,
                                                plot_no: $scope.dispatch_filter.plot_no,
                                                wo_no: $scope.dispatch_filter.wo_no,
                                                plot_end_time: $scope.dispatch_filter.plot_end_time,
                                                item_no: $scope.dispatch_filter.item_no,
                                                item_name: $scope.dispatch_filter.item_name,
                                                item_spec: $scope.dispatch_filter.item_spec,
                                                mono_date: $scope.dispatch_filter.mono_date,
                                                op_no: $scope.dispatch_filter.op_no,
                                                op_name: $scope.dispatch_filter.op_name
                                        };
                                        search({ return_type: '0110' });
                                }
                        }
                        
                        // 20230911 modify by Alan for #136071: 換頁不清除勾選狀態
                        // 实体分页查询功能实现 20221116 modify by shiwl  for M#18991  上一页事件
                        $scope.previous = function () {
                                if ($scope.pageSetting.PageNumber - 1 <= 0) {
                                        $scope.pageSetting.PageNumber = 1;
                                } else {
                                        $scope.pageSetting.PageNumber = $scope.pageSetting.PageNumber - 1;
                                        search({ return_type: '0110', cleanCache: false });
                                }
                        };

                        // 实体分页查询功能实现 20221116 modify by shiwl  for M#18991  下一页事件
                        $scope.next = function () {
                                if ($scope.pageSetting.PageNumber + 1 > ($scope.pageSetting.TotalPage)) {
                                        $scope.pageSetting.PageNumber = $scope.pageSetting.TotalPage;

                                } else {
                                        $scope.pageSetting.PageNumber = $scope.pageSetting.PageNumber + 1;
                                        search({ return_type: '0110', cleanCache: false });
                                }
                        };
                        $scope.init = function () {

                                $scope.changeHeight();
                                // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
                                $scope.showMode = "query"
                                $scope.printList = []; // 列印詳情

                                $MMWService.PNIGList = {};
                                $scope.work_date = new Date();//工作時間
                                $scope.order_by_mode = { name: "", sort: false };
                                // 20201221 FOR 83491 自定义排版
                                // 派工
                                // 20211217 modify by Alan for#104583 : 刪除last_date與next_date
                                $scope.settingList = [
                                        'op_no', 'op_name', 'wo_no', 'plot_no', 'qty', 'plot_start_time', 'plot_end_time', 'item_no', 'item_name', 'item_spec', 'mono_date', 'accessory_no',
                                        'item_version', 'BaseProcessNo', 'BaseProcessVersion', 'BoxQty', 'CUSTOMERNO', 'CartonQty', 'ERPMoLineNo', 'FACTORYNO', 'GRAPHNO', 'HotLot', 'ITEMNO', 'LOTDescription', 'LOTPriority',
                                        'LOTSTDQty', 'LOTplanstartdate', 'MOPRIORITY', 'MOUNITNO', 'MOplanstartdate', 'MPQty', 'MoDescription', 'MoSource', 'MoUser_Defined01', 'MoUser_Defined02', 'MoUser_Defined03', 'MoUser_Defined04', 'MoUser_Defined05',
                                        'MoUser_Defined11', 'MoUser_Defined12', 'MoUser_Defined13', 'MoUser_Defined21', 'MoUser_Defined22', 'MoUser_Defined23', 'PRODUCTTYPE', 'PalletQty', 'PrdDescription', 'PrdUser_Defined01',
                                        'PrdUser_Defined02', 'PrdUser_Defined03', 'PrdUser_Defined04', 'PrdUser_Defined05', 'PrdUser_Defined11', 'PrdUser_Defined12', 'PrdUser_Defined13', 'PrdUser_Defined21', 'PrdUser_Defined22',
                                        'PrdUser_Defined23', 'PriceType', 'ProductCode', 'ProductPCSNo', 'QCCategory', 'RONO', 'SerialTypeNo_COMP', 'SerialTypeNo_LOT', 'SpecNo', 'StockInLotNo', 'Storage_Spaces_No', 'Warehouse_No'
                                ];
                                // 已派工
                                // 20211217 modify by Alan for#104583 : 刪除last_date與next_date
                                $scope.dispatchedSettingList = [
                                        'op_no', 'op_name', 'wo_no', 'plot_no', 'plot_qty', 'uncheck_in_qty', 'plot_start_time', 'plot_end_time', 'dis_start_time', 'disp_end_time', 'item_no', 'item_name', 'batch_mark', 'item_spec', 'tc_rate', 'tc_rate_for_all', 'c_rate_for_all', 'mono_date',
                                        'MOplanstartdate', 'CUSTOMERNO', 'RONO', 'ITEMNO', 'MOPRIORITY', 'MOUNITNO', 'MoDescription', 'MoSource', 'FACTORYNO', 'StockInLotNo', 'Warehouse_No', 'Storage_Spaces_No', 'ERPMoLineNo',
                                        'MoUser_Defined01', 'MoUser_Defined02', 'MoUser_Defined03', 'MoUser_Defined04', 'MoUser_Defined05', 'MoUser_Defined11', 'MoUser_Defined12', 'MoUser_Defined13', 'MoUser_Defined21', 'MoUser_Defined22', 'MoUser_Defined23',
                                        'PRODUCTTYPE', 'SpecNo', 'GRAPHNO', 'PrdDescription', 'CartonQty', 'PalletQty', 'BoxQty', 'ProductCode', 'SerialTypeNo_LOT', 'SerialTypeNo_COMP', 'LOTSTDQty', 'PrdUser_Defined01', 'PrdUser_Defined02', 'PrdUser_Defined03',
                                        'PrdUser_Defined04', 'PrdUser_Defined05', 'PrdUser_Defined11', 'PrdUser_Defined12', 'PrdUser_Defined13', 'PrdUser_Defined21', 'PrdUser_Defined22', 'PrdUser_Defined23', 'QCCategory', 'ProductPCSNo', 'MPQty', 'LOTPriority',
                                        'HotLot', 'LOTDescription', 'LOTplanstartdate', 'PriceType', 'BaseProcessNo', 'BaseProcessVersion'
                                ];
                                $scope.packList = [];
                                $scope.moreInfoList = [];
                                $scope.showTipsFlag = false;
                                $scope.tempRow = {};
                                $scope.tempDispatchRow = {};

                                $scope.dispatchedPackList = [];
                                $scope.dispatchedMoreInfoList = [];
                                $scope.dispatchedShowTipsFlag = false;
                                $scope.dispatchedTempRow = {};

                               


                                // 20211217 modify by Alan for#104583 : 刪除last_date與next_date
                                $scope.show_flag = {
                                        op_no: false,
                                        op_name: false,
                                        wo_no: false,
                                        plot_no: false,
                                        qty: false,
                                        plot_start_time: false,
                                        plot_end_time: false,
                                        item_no: false,
                                        item_name: false,
                                        item_spec: false,
                                        mono_date: false,
                                        accessory_no: false,
                                        item_version: false,
                                        BaseProcessNo: false,
                                        BaseProcessVersion: false,
                                        BoxQty: false,
                                        CUSTOMERNO: false,
                                        CartonQty: false,
                                        ERPMoLineNo: false,
                                        FACTORYNO: false,
                                        GRAPHNO: false,
                                        HotLot: false,
                                        ITEMNO: false,
                                        LOTDescription: false,
                                        LOTPriority: false,
                                        LOTSTDQty: false,
                                        LOTplanstartdate: false,
                                        MOPRIORITY: false,
                                        MOUNITNO: false,
                                        MOplanstartdate: false,
                                        MPQty: false,
                                        MoDescription: false,
                                        MoSource: false,
                                        MoUser_Defined01: false,
                                        MoUser_Defined02: false,
                                        MoUser_Defined03: false,
                                        MoUser_Defined04: false,
                                        MoUser_Defined05: false,
                                        MoUser_Defined11: false,
                                        MoUser_Defined12: false,
                                        MoUser_Defined13: false,
                                        MoUser_Defined21: false,
                                        MoUser_Defined22: false,
                                        MoUser_Defined23: false,
                                        PRODUCTTYPE: false,
                                        PalletQty: false,
                                        PrdDescription: false,
                                        PrdUser_Defined01: false,
                                        PrdUser_Defined02: false,
                                        PrdUser_Defined03: false,
                                        PrdUser_Defined04: false,
                                        PrdUser_Defined05: false,
                                        PrdUser_Defined11: false,
                                        PrdUser_Defined12: false,
                                        PrdUser_Defined13: false,
                                        PrdUser_Defined21: false,
                                        PrdUser_Defined22: false,
                                        PrdUser_Defined23: false,
                                        PriceType: false,
                                        ProductCode: false,
                                        ProductPCSNo: false,
                                        QCCategory: false,
                                        RONO: false,
                                        SerialTypeNo_COMP: false,
                                        SerialTypeNo_LOT: false,
                                        SpecNo: false,
                                        StockInLotNo: false,
                                        Storage_Spaces_No: false,
                                        Warehouse_No: false
                                };
                                // 20211217 modify by Alan for#104583 : 刪除last_date與next_date
                                $scope.dispatched_show_flag = {
                                        op_no: false,
                                        op_name: false,
                                        wo_no: false,
                                        plot_no: false,
                                        plot_qty: false,
                                        uncheck_in_qty: false,
                                        plot_start_time: false,
                                        plot_end_time: false,
                                        dis_start_time: false,
                                        disp_end_time: false,
                                        item_no: false,
                                        item_name: false,
                                        batch_mark: false,
                                        item_spec: false,
                                        tc_rate: false,
                                        tc_rate_for_all: false,
                                        c_rate_for_all: false,
                                        mono_date: false,
                                        MOplanstartdate: false,
                                        CUSTOMERNO: false,
                                        RONO: false,
                                        ITEMNO: false,
                                        MOPRIORITY: false,
                                        MOUNITNO: false,
                                        MoDescription: false,
                                        MoSource: false,
                                        FACTORYNO: false,
                                        StockInLotNo: false,
                                        Warehouse_No: false,
                                        Storage_Spaces_No: false,
                                        ERPMoLineNo: false,
                                        MoUser_Defined01: false,
                                        MoUser_Defined02: false,
                                        MoUser_Defined03: false,
                                        MoUser_Defined04: false,
                                        MoUser_Defined05: false,
                                        MoUser_Defined11: false,
                                        MoUser_Defined12: false,
                                        MoUser_Defined13: false,
                                        MoUser_Defined21: false,
                                        MoUser_Defined22: false,
                                        MoUser_Defined23: false,
                                        PRODUCTTYPE: false,
                                        SpecNo: false,
                                        GRAPHNO: false,
                                        PrdDescription: false,
                                        CartonQty: false,
                                        PalletQty: false,
                                        BoxQty: false,
                                        ProductCode: false,
                                        SerialTypeNo_LOT: false,
                                        SerialTypeNo_COMP: false,
                                        LOTSTDQty: false,
                                        PrdUser_Defined01: false,
                                        PrdUser_Defined02: false,
                                        PrdUser_Defined03: false,
                                        PrdUser_Defined04: false,
                                        PrdUser_Defined05: false,
                                        PrdUser_Defined11: false,
                                        PrdUser_Defined12: false,
                                        PrdUser_Defined13: false,
                                        PrdUser_Defined21: false,
                                        PrdUser_Defined22: false,
                                        PrdUser_Defined23: false,
                                        QCCategory: false,
                                        ProductPCSNo: false,
                                        MPQty: false,
                                        LOTPriority: false,
                                        HotLot: false,
                                        LOTDescription: false,
                                        LOTplanstartdate: false,
                                        PriceType: false,
                                        BaseProcessNo: false,
                                        BaseProcessVersion: false
                                };
                                // 20211217 modify by Alan for#104583 : 刪除last_date與next_date
                                $scope.show_label = {
                                        op_no: '',
                                        op_name: '',
                                        wo_no: '',
                                        plot_no: '',
                                        qty: '',
                                        plot_start_time: '',
                                        plot_end_time: '',
                                        item_no: '',
                                        item_name: '',
                                        item_spec: '',
                                        mono_date: '',
                                        accessory_no: '',
                                        item_version: '',
                                        BaseProcessNo: '',
                                        BaseProcessVersion: '',
                                        BoxQty: '',
                                        CUSTOMERNO: '',
                                        CartonQty: '',
                                        ERPMoLineNo: '',
                                        FACTORYNO: '',
                                        GRAPHNO: '',
                                        HotLot: '',
                                        ITEMNO: '',
                                        LOTDescription: '',
                                        LOTPriority: '',
                                        LOTSTDQty: '',
                                        LOTplanstartdate: '',
                                        MOPRIORITY: '',
                                        MOUNITNO: '',
                                        MOplanstartdate: '',
                                        MPQty: '',
                                        MoDescription: '',
                                        MoSource: '',
                                        MoUser_Defined01: '',
                                        MoUser_Defined02: '',
                                        MoUser_Defined03: '',
                                        MoUser_Defined04: '',
                                        MoUser_Defined05: '',
                                        MoUser_Defined11: '',
                                        MoUser_Defined12: '',
                                        MoUser_Defined13: '',
                                        MoUser_Defined21: '',
                                        MoUser_Defined22: '',
                                        MoUser_Defined23: '',
                                        PRODUCTTYPE: '',
                                        PalletQty: '',
                                        PrdDescription: '',
                                        PrdUser_Defined01: '',
                                        PrdUser_Defined02: '',
                                        PrdUser_Defined03: '',
                                        PrdUser_Defined04: '',
                                        PrdUser_Defined05: '',
                                        PrdUser_Defined11: '',
                                        PrdUser_Defined12: '',
                                        PrdUser_Defined13: '',
                                        PrdUser_Defined21: '',
                                        PrdUser_Defined22: '',
                                        PrdUser_Defined23: '',
                                        PriceType: '',
                                        ProductCode: '',
                                        ProductPCSNo: '',
                                        QCCategory: '',
                                        RONO: '',
                                        SerialTypeNo_COMP: '',
                                        SerialTypeNo_LOT: '',
                                        SpecNo: '',
                                        StockInLotNo: '',
                                        Storage_Spaces_No: '',
                                        Warehouse_No: ''
                                };
                                // 20211217 modify by Alan for#104583 : 刪除last_date與next_date
                                $scope.dispatched_show_label = {
                                        op_no: '',
                                        op_name: '',
                                        wo_no: '',
                                        plot_no: '',
                                        plot_qty: '',
                                        uncheck_in_qty: '',
                                        plot_start_time: '',
                                        plot_end_time: '',
                                        dis_start_time: '',
                                        disp_end_time: '',
                                        item_no: '',
                                        item_name: '',
                                        batch_mark: '',
                                        item_spec: '',
                                        tc_rate: '',
                                        tc_rate_for_all: '',
                                        c_rate_for_all: '',
                                        mono_date: '',
                                        MOplanstartdate: '',
                                        CUSTOMERNO: '',
                                        RONO: '',
                                        ITEMNO: '',
                                        MOPRIORITY: '',
                                        MOUNITNO: '',
                                        MoDescription: '',
                                        MoSource: '',
                                        FACTORYNO: '',
                                        StockInLotNo: '',
                                        Warehouse_No: '',
                                        Storage_Spaces_No: '',
                                        ERPMoLineNo: '',
                                        MoUser_Defined01: '',
                                        MoUser_Defined02: '',
                                        MoUser_Defined03: '',
                                        MoUser_Defined04: '',
                                        MoUser_Defined05: '',
                                        MoUser_Defined11: '',
                                        MoUser_Defined12: '',
                                        MoUser_Defined13: '',
                                        MoUser_Defined21: '',
                                        MoUser_Defined22: '',
                                        MoUser_Defined23: '',
                                        PRODUCTTYPE: '',
                                        SpecNo: '',
                                        GRAPHNO: '',
                                        PrdDescription: '',
                                        CartonQty: '',
                                        PalletQty: '',
                                        BoxQty: '',
                                        ProductCode: '',
                                        SerialTypeNo_LOT: '',
                                        SerialTypeNo_COMP: '',
                                        LOTSTDQty: '',
                                        PrdUser_Defined01: '',
                                        PrdUser_Defined02: '',
                                        PrdUser_Defined03: '',
                                        PrdUser_Defined04: '',
                                        PrdUser_Defined05: '',
                                        PrdUser_Defined11: '',
                                        PrdUser_Defined12: '',
                                        PrdUser_Defined13: '',
                                        PrdUser_Defined21: '',
                                        PrdUser_Defined22: '',
                                        PrdUser_Defined23: '',
                                        QCCategory: '',
                                        ProductPCSNo: '',
                                        MPQty: '',
                                        LOTPriority: '',
                                        HotLot: '',
                                        LOTDescription: '',
                                        LOTplanstartdate: '',
                                        PriceType: '',
                                        BaseProcessNo: '',
                                        BaseProcessVersion: '',
                                };
                                if (localStorage.getItem('customLayout')) { 
                                        var settingsList = JSON.parse(localStorage.getItem('customLayout'));
                                        var settingsIdx = settingsList.findIndex(function (item) {
                                                return item.page_id == 'WIP007' && item.div_id == 'undsplist';
                                        });
                                        if (settingsIdx !== -1 && settingsList[settingsIdx].view_desc) {
                                                let tempList = JSON.parse(settingsList[settingsIdx].view_desc).data;
                                                tempList.forEach(t => {
                                                        $scope.packList.push(t.col[0]);
                                                });
                                                $scope.moreInfoList = JSON.parse(settingsList[settingsIdx].view_desc).list;
                                        }
                                        if ($scope.packList.length > 0) {
                                                $scope.packList.forEach(p => {
                                                        let data = $scope.settingList.filter(l => p.fieldId == l);
                                                        if (data.length > 0) {
                                                                $scope.show_flag[p.fieldId] = true;
                                                                $scope.show_label[p.fieldId] = p.fieldName;
                                                        }
                                                });
                                        } else {
                                                $scope.getInitData();
                                        }

                                        // 已派工
                                        var dispatchedSettingsIdx = settingsList.findIndex(function (item) {
                                                return item.page_id == 'WIP007' && item.div_id == 'ondsplist';
                                        });
                                        if (dispatchedSettingsIdx !== -1 && settingsList[dispatchedSettingsIdx].view_desc) {
                                                let tempList = JSON.parse(settingsList[dispatchedSettingsIdx].view_desc).data;
                                                tempList.forEach(t => {
                                                        $scope.dispatchedPackList.push(t.col[0]);
                                                });
                                                $scope.dispatchedMoreInfoList = JSON.parse(settingsList[dispatchedSettingsIdx].view_desc).list;
                                        }
                                        if ($scope.dispatchedPackList.length > 0) {
                                                $scope.dispatchedPackList.forEach(p => {
                                                        let data = $scope.dispatchedSettingList.filter(l => p.fieldId == l);
                                                        if (data.length > 0) {
                                                                $scope.dispatched_show_flag[p.fieldId] = true;
                                                                $scope.dispatched_show_label[p.fieldId] = p.fieldName;
                                                        }
                                                });
                                        } else {
                                                $scope.getDispatchedInitData();
                                        }
                                } else {
                                        $scope.getInitData();
                                        $scope.getDispatchedInitData();
                                }
                                // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
                                // step 1. 取得區域
                                $scope.loadAreaInfo();
                                $scope.dashboard = {
                                        dispatch: {
                                                // templateUrl: 'module/moduleA/program/A07/A07_dispatch.html'
                                                templateUrl: ''
                                        },
                                        dispatched: {
                                                // templateUrl: 'module/moduleA/program/A07/A07_dispatched.html'
                                                templateUrl: ''
                                        }
                                }
                        };

                        // 20211217 modify by Alan for#104583 : 刪除last_date與next_date
                        $scope.getInitData = function () {
                                $scope.show_flag.op_no = true;
                                $scope.show_flag.op_name = true;
                                $scope.show_flag.wo_no = true;
                                $scope.show_flag.plot_no = true;
                                $scope.show_flag.qty = true;
                                $scope.show_flag.plot_start_time = true;
                                $scope.show_flag.plot_end_time = true;
                                $scope.show_flag.item_no = true;
                                $scope.show_flag.item_name = true;
                                $scope.show_flag.item_spec = true;
                                $scope.show_flag.mono_date = true;
                                $scope.show_flag.accessory_no = true;
                                $scope.show_label.op_no = $filter('translate')('A02.list.column1');
                                $scope.show_label.op_name = $filter('translate')('A02.list.column2');
                                $scope.show_label.wo_no = $filter('translate')('A02.list.column12');
                                $scope.show_label.plot_no = $filter('translate')('A02.list.column3');
                                $scope.show_label.qty = $filter('translate')('A02.list.column4');
                                $scope.show_label.plot_start_time = $filter('translate')('A02.list.column7');
                                $scope.show_label.plot_end_time = $filter('translate')('A02.list.column8');
                                $scope.show_label.item_no = $filter('translate')('A02.list.column5');
                                $scope.show_label.item_name = $filter('translate')('A02.list.column6');
                                $scope.show_label.item_spec = $filter('translate')('A02.list.column13');
                                $scope.show_label.mono_date = $filter('translate')('A02.list.column16');
                                $scope.show_label.accessory_no = $filter('translate')('A02.list.column17');
                        };

                        // 20211217 modify by Alan for#104583 : 刪除last_date與next_date
                        // 20221017 modify by Alan for#118298 : tc_rate，tc_rate_for_all，c_rate_for_all暫時不會用到
                        $scope.getDispatchedInitData = function () {
                                $scope.dispatched_show_flag.op_no = true,
                                        $scope.dispatched_show_flag.op_name = true,
                                        $scope.dispatched_show_flag.wo_no = true,
                                        $scope.dispatched_show_flag.plot_no = true,
                                        $scope.dispatched_show_flag.plot_qty = true,
                                        $scope.dispatched_show_flag.uncheck_in_qty = true,
                                        $scope.dispatched_show_flag.plot_start_time = true,
                                        $scope.dispatched_show_flag.plot_end_time = true,
                                        $scope.dispatched_show_flag.dis_start_time = true,
                                        $scope.dispatched_show_flag.disp_end_time = true,
                                        $scope.dispatched_show_flag.item_no = true,
                                        $scope.dispatched_show_flag.item_name = true,
                                        $scope.dispatched_show_flag.batch_mark = true,
                                        $scope.dispatched_show_flag.item_spec = true,
                                        $scope.dispatched_show_flag.tc_rate = false,
                                        $scope.dispatched_show_flag.tc_rate_for_all = false,
                                        $scope.dispatched_show_flag.c_rate_for_all = false,
                                        $scope.dispatched_show_flag.mono_date = true,
                                        $scope.dispatched_show_label.op_no = $filter('translate')('customLayout.ondsplist.column0'),
                                        $scope.dispatched_show_label.op_name = $filter('translate')('customLayout.ondsplist.column1'),
                                        $scope.dispatched_show_label.wo_no = $filter('translate')('customLayout.ondsplist.column2'),
                                        $scope.dispatched_show_label.plot_no = $filter('translate')('customLayout.ondsplist.column3'),
                                        $scope.dispatched_show_label.plot_qty = $filter('translate')('customLayout.ondsplist.column4'),
                                        $scope.dispatched_show_label.uncheck_in_qty = $filter('translate')('customLayout.ondsplist.column5'),
                                        $scope.dispatched_show_label.plot_start_time = $filter('translate')('customLayout.ondsplist.column6'),
                                        $scope.dispatched_show_label.plot_end_time = $filter('translate')('customLayout.ondsplist.column7'),
                                        $scope.dispatched_show_label.dis_start_time = $filter('translate')('customLayout.ondsplist.column8'),
                                        $scope.dispatched_show_label.disp_end_time = $filter('translate')('customLayout.ondsplist.column9'),
                                        $scope.dispatched_show_label.item_no = $filter('translate')('customLayout.ondsplist.column10'),
                                        $scope.dispatched_show_label.item_name = $filter('translate')('customLayout.ondsplist.column11'),
                                        $scope.dispatched_show_label.batch_mark = $filter('translate')('customLayout.ondsplist.column12'),
                                        $scope.dispatched_show_label.item_spec = $filter('translate')('customLayout.ondsplist.column13'),
                                        $scope.dispatched_show_label.tc_rate = $filter('translate')('customLayout.ondsplist.column14'),
                                        $scope.dispatched_show_label.tc_rate_for_all = $filter('translate')('customLayout.ondsplist.column15'),
                                        $scope.dispatched_show_label.c_rate_for_all = $filter('translate')('customLayout.ondsplist.column16'),
                                        $scope.dispatched_show_label.mono_date = $filter('translate')('customLayout.ondsplist.column19')
                        };

                        // 显示派工Tips
                        $scope.showTips = function (item, e, i) {
                                $scope.tempRow = item;
                                e.preventDefault();
                                e.stopPropagation();
                                $scope.showTipsFlag = true;
                                var popovertip = angular.element(document.getElementById('popover_id'));
                                var index = document.getElementById('item' + i);
                                popovertip.css('display', 'block');
                                popovertip.css('top', $(index).offset().top + 5 + 'px');
                                popovertip.css('left', $(index).offset().left + 'px');

                        }
                        // 隐藏派工Tips
                        $scope.hideTips = function (item, e) {
                                e.preventDefault();
                                e.stopPropagation();
                                $scope.showTipsFlag = false;
                                $scope.tempRow = {};
                        }

                        // 显示待排Tips
                        $scope.showDispatchTips = function (item, e, i) {
                                $scope.dispatchedTempRow = item;
                                e.preventDefault();
                                e.stopPropagation();
                                $scope.dispatchedShowTipsFlag = true;
                                var popovertip = angular.element(document.getElementById('popover_id_wait'));
                                var index = document.getElementById('item' + i);
                                popovertip.css('display', 'block');
                                popovertip.css('top', $(index).offset().top + 30 + 'px');
                                popovertip.css('left', $(index).offset().left + 20 + 'px');

                        }
                        // 隐藏待排Tips
                        $scope.hideDispatchTips = function (item, e) {
                                e.preventDefault();
                                e.stopPropagation();
                                $scope.dispatchedShowTipsFlag = false;
                                $scope.dispatchedTempRow = {};
                        }

                        // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
                        $scope.loadAreaInfo = function () {
                                // 取得區域列表
                                $MMWService.pageNumberInfoGet({
                                        page_mode: '54',
                                        query_condition_info: [
                                                { column_name: 'A.MASTERNO', query_mode: '0', value: config.cache.account, merge_condition_model: 'AND' }
                                        ],
                                }, function (itemList) {
                                        if (itemList.length <= 0) {
                                                $scope.$root.showAlert($filter('translate')('A02.msg.noArea1'));
                                                return;
                                        }

                                        $scope.area_detail = itemList;
                                        $scope.selectareaNo = $scope.area_detail[0].page_no;
                                        $scope.selectareaName = $scope.area_detail[0].page_no + ' (' + $scope.area_detail[0].page_name + ')';
                                        $scope.isLine = $scope.area_detail[0].area_type || '0';
                                        $scope.selectWorkStation = '';
                                        $scope.selectWorkStationName = '';
                                        $scope.op_group_detail = [];

                                        // 获取默认生产批状态

                                        var LotState = JSON.parse(localStorage.getItem($scope.selectareaNo));
                                                                
                                       
                                        if (LotState){
                                         $scope.initPlotNoStatus = LotState.label;

                                         $scope.project_status_code = LotState.code;
                                        }


                                        //step 2. 把第一筆區域當成預設值並帶入search 內查詢出資訊
                                        // 先查op_list 再查 undispatched_list跟machine_statistcs_list
                                        search({ return_type: '1000' }, function () {
                                                search({ return_type: '0120' });
                                        });
                                });
                        }


                        // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
                        $scope.loadMyFavorites = function () {
                                $MMWService.showQueryListPNIG({
                                        page_mode: 53,
                                        mode: 'M',
                                        key: 'page_no',
                                        header: [
                                                { label: $filter('translate')('common.queryList.area_c'), code: 'page_no' },
                                                { label: $filter('translate')('common.queryList.area_n'), code: 'page_name' }
                                        ],
                                        selectKey: { key: 'isselect', true: '1', false: '0' },
                                        setCondition: function (conditions) {
                                                conditions.push({ column_name: 'MASTERNO', query_mode: '0', value: config.cache.account, merge_condition_model: 'AND' });
                                                return conditions;
                                        },
                                        confirm: function (selectItem, dialog) {
                                                // 向数据库插入我的最爱数据信息
                                                var content = {
                                                        master_no: config.cache.account, // 用户编号
                                                        master_type: 7,
                                                        favourite_user_area: []
                                                };
                                                selectItem.forEach(function (item) {
                                                        if (item.isselect == '1') {
                                                                content.favourite_user_area.push({ area_no: item.page_no });
                                                        }
                                                });
                                                if (content.favourite_user_area.length == 0) {
                                                        $scope.$root.showAlert($filter('translate')('A02.msg.lessThan'));
                                                } else {
                                                        $MMWService.sendToServer({
                                                                uri: 'ServicesSTD.Module_SYS.favourite_machine_process',
                                                                content: content,
                                                                success: function (data) {
                                                                        dialog.hide();
                                                                        $scope.loadAreaInfo();
                                                                }
                                                        });
                                                }
                                        }
                                });
                        };
                        // 加载自定义排版
                        $scope.loadSysSettings = function () {
                                // 取得未派顯示欄位
                                const columns = [];
                                for(let key in $scope._event) {
                                        // 要過濾的欄位
                                        const hiddenColumns = ['dispatch_detail.acc_detail', 'dispatch_detail.item_send_work', 'dispatch_detail.lst_accessory'];
                                        const isShow =
                                        key.includes("dispatch_detail.") &&
                                        !hiddenColumns.includes(key) &&
                                        $scope._event[key].isShown != "N";
                                        if (isShow) {
                                        columns.push({
                                                code: key.split(".")[1],
                                                label: $scope._event[key].displayText,
                                        });
                                        }
                                }
                                $mdDialog.serviceDialog('customOrderService', {
                                        listName: 'dispatch_detail',
                                        columns: [
                                                {"code":"op_no","label": $filter('translate')('A08.list.column1')},
                                                {"code":"op_name","label":$filter('translate')('A08.list.column2')},
                                                {"code":"wo_no","label":$filter('translate')('A08.list.column3')},
                                                {"code":"plot_no","label":$filter('translate')('A08.list.column4')},
                                                {"code":"qty","label":$filter('translate')('A08.list.column5')},
                                                {"code":"plot_start_time","label":$filter('translate')('A08.list.column6')},
                                                {"code":"plot_end_time","label":$filter('translate')('A08.list.column7')},
                                                {"code":"item_no","label":$filter('translate')('A08.list.column8')},
                                                {"code":"item_name","label":$filter('translate')('A08.list.column9')},
                                                {"code":"item_spec","label":$filter('translate')('A08.list.column10')},
                                                {"code":"mono_date","label":$filter('translate')('A08.list.column11')}],
                                        callback: function() {
                                        // 更新未派訊息
                                        search({ return_type: '0110' })
                                        }
                                });
                        };

                        $scope.back = function () {
                                $scope.$root.hideMenu();
                                $scope.$root.changeProgram('home', true);
                        };
                        $scope.orderbychange = function (mode) {
                                //console.log($scope.order_by_mode);
                                if ($scope.order_by_mode.name != mode) {
                                        $scope.order_by_mode.name = mode;
                                        $scope.order_by_mode.sort = false;
                                }
                                else {
                                        if ($scope.order_by_mode.sort)
                                                $scope.order_by_mode.sort = false;
                                        else
                                                $scope.order_by_mode.sort = true;
                                }

                        }

                        function search(option, feedback) {
                                // return type:
                                // 1000 => op_list  查作业站
                                // 0100 => undispatched_list
                                // 0010 => machine_statistcs_list
                                // 0001 => dispatched_list
                                // 0020 => 派工EXCEL
                               

                                // 檢查是否有區域訊息
                                if ($scope.area_detail.length == 0) {
                                        // 派工区域尚未设定我的最爱，请问是否要现在设定？
                                        var msg = $filter('translate')('A02.alert.msg2');
                                        $scope.$root.showConfirm(msg, function (dialog) {
                                                dialog.hide();
                                                $scope.loadMyFavorites();

                                        });
                                        return;
                                }

                                let content = angular.merge(
                                        {
                                                area_no: $scope.selectareaNo,
                                                pageSetting: $scope.pageSetting,
                                                lst_opno: [],
                                                work_date: $scope.conditions.pack_date_start,
                                                lst_machine_no:$scope.machine_detail.map(item=>item.machine_no),
                                                work_start_date:$scope.conditions.pack_date_start,
                                                work_end_date: $scope.conditions.pack_date_end,
                                                machine_statistics_condition: {
                                                        wo_no: "",
                                                        plot_no: "",
                                                        machine_no: "",
                                                        is_capacity: true
                                                },
                                                dispatched_condition: {
                                                        wo_no: "",
                                                        plot_no: "",
                                                        machine_no: "",
                                                },
                                                undispatched_condition: {
                                                        wo_no: "",
                                                        plot_no: "",
                                                        is_capacity: true
                                                },
                                                HotLot:$scope.do_flag,  // 紧急批
                                                LotState: $scope.project_status_code // 生产批状态
                                        },
                                        option
                                );
                                // 实体分页查询 20221116 
                                var target = Object.assign(content.undispatched_condition, targetData);
                                content.undispatched_condition = target;
                                let lst_opno= [];
                                                $scope.op_group_detail.map(item =>{
                                                   if(item.is_select=='true'){
                                                        lst_opno.push(item.op_no)  
                                                   }
                                                } )
                                        content = angular.merge(content, {
                                                lst_opno: lst_opno
                                        });
                                // undispatched_list或machine_statistcs_list或dispatched_list 要帶lst_opno
                                if (content.return_type.charAt(1) === '1'
                                        || content.return_type.charAt(2) === '1'
                                        || content.return_type.charAt(3) === '1') {
                                                
                                }

                                // undispatched_list 未派列表
                                if (content.return_type.charAt(1) === '1') {
                                        content = angular.merge(
                                                content,
                                                {
                                                        undispatched_condition: {
                                                                wo_no: $scope.unassigned_wo_no || "",
                                                                plot_no: $scope.unassigned_plot_no || "",
                                                        }
                                                }
                                        );
                                        // 取得未派排序設定
                                        content.undispatched_condition.sort = customOrderService.getSettings('dispatch_detail');
                                }

                                // machine_statistcs_list 設備列表
                                if (content.return_type.charAt(2) === '1' || content.return_type.charAt(2) === '2') {
                                       
                                        content = angular.merge(
                                                content,
                                                {
                                                        machine_statistics_condition: {
                                                                wo_no: $scope.assigned_wo_no || "",
                                                                plot_no: $scope.assigned_plot_no || "",
                                                                machine_no: $scope.assigned_machine || "",
                                                                is_capacity: true,
                                                                equipment_sort_mode_label:$scope.equipment_sort_mode
                                                        },
                                                }
                                        );
                                }

                                // dispatched_list 已派列表
                                if (content.return_type.charAt(3) === '1' ||  content.return_type.charAt(1) === '2') {
                                        content = angular.merge(
                                                content,
                                                {
                                                        dispatched_condition: {
                                                                wo_no: $scope.assigned_wo_no || "",
                                                                plot_no: $scope.assigned_plot_no || "",
                                                                machine_no: $scope.assigned_machine || "",
                                                        },
                                                }
                                        );
                                }

                                //當有設定已派工查詢條件時，不可變更已派工順序
                                $scope.is_lock_sort = (content.dispatched_condition.wo_no == '' && content.dispatched_condition.plot_no == '');

                                $MMWService.sendToServer({
                                        uri: "ServicesSTD.Module_WIP.dispatch_area_info_new_get",
                                        content: content,
                                        success: function (data) {
                                                var errorMsg = '';
                                                if (content.return_type.charAt(1) === '2') {
                                                      console.log(data);

                                                      $scope.list = data.dispatchedExcel_list;

                                                    //  $scope.excelListCopy = JSON.parse(JSON.stringify(data.dispatchedExcel_list));
                                                     

                                                }
                                                // op_list 作業站列表
                                                if (content.return_type.charAt(0) === '1') {
                                                        $scope.pluginType = data.op_list.length>0 ? data.op_list[0].plugin:"";
                                                        //M#95547 熱處理優化 爐量顯示
                                                        var op_has_ht = 0;  // 熱處理 作業站計數
                                                        $scope.selectWorkStationName = '';
                                                        $scope.op_group_detail = data.op_list;
                                                      
                                                        if ($scope.op_group_detail && $scope.op_group_detail.length > 0) {
                                                                //M#95547 熱處理優化 爐量顯示
                                                                var op_has_ht = 0;  // 熱處理 作業站計數
                                                                $scope.op_group_detail.forEach(function (item) {
                                                                        if (item.is_select == 'true')
                                                                                $scope.selectWorkStationName += item.op_name + ' \\ ';
                                                                        if (item.plugin == 1) // plugin == 1 == 熱處理 作業站
                                                                                op_has_ht++;
                                                                });
                                                                //判斷是否有熱處理作業站  大於 0 顯示爐量 
                                                                if (op_has_ht > 0)
                                                                        $scope.ht_tr_bool = true;
                                                                else
                                                                        $scope.ht_tr_bool = false;
                                                                $scope.selectWorkStationName = $scope.selectWorkStationName.substr(0, $scope.selectWorkStationName.length - 3);
                                                        }
                                                }

                                                // undispatched_list 未派列表
                                                if (content.return_type.charAt(1) === '1') {
                                                        // 20230911 modify by Alan for #136071: 有查詢未派時，才更新頁數
                                                        $scope.pageSetting.TotalPage = data.undispatched_list_totalPage;

                                                        // 20230911 modify by Alan for #136071: 預設清除已選暫存
                                                        if (option.cleanCache === undefined || option.cleanCache) {
                                                                dispatch_detail_checked = [];
                                                        }
                                                        // 初始化未派列表
                                                        if (!$scope.dashboard.dispatch.templateUrl) {
                                                                $timeout(() => {
                                                                        $scope.dashboard.dispatch.templateUrl = 'module/moduleA/program/A08/A08_dispatch.html';
                                                                })
                                                        }
                                                        $scope.dispatch_detail = data.undispatched_list;
                                                        if ($scope.dispatch_detail.length == 0) {
                                                                if (content.dispatched_condition.wo_no == ''
                                                                        && content.dispatched_condition.plot_no == '') {
                                                                        errorMsg += $filter('translate')('A02.msg.B0201first') + '<br>';
                                                                } else {
                                                                        errorMsg += $filter('translate')('common.msg.no_data') + '<br>';
                                                                }
                                                        } else {
                                                                // 20230911 modify by Alan for #136071: 增加跨頁選中功能
                                                                // 從暫存中取出選擇的資料，還原到已派工列表
                                                                for(let item of dispatch_detail_checked) {
                                                                        if(item._page === $scope.pageSetting.PageNumber) {
                                                                                let index = $scope.dispatch_detail.findIndex(temp => temp.plot_no == item.plot_no && temp.op_no == item.op_no);
                                                                                if (index != -1) {
                                                                                        $scope.dispatch_detail[index].checked = 'Y';
                                                                                } else {
                                                                                        $scope.$root.showAlert($filter('translate')('A08.showAlert.undispatch_changed'));
                                                                                        $scope.dispatch_detail = angular.merge([], data.undispatched_list);
                                                                                        dispatch_detail_checked = [];
                                                                                        $scope.Mode = '';
                                                                                        return;
                                                                                }
                                                                        }
                                                                }
                                                                
                                                                let thisPageChecked = $scope.dispatch_detail.filter(item => item.checked);
                                                                $scope.select_all_bool = thisPageChecked.length === $scope.dispatch_detail.length;
                                                        }
                                                      
                                                }

                                                // machine_statistcs_list 設備列表
                                                if (content.return_type.charAt(2) === '2') {

                                                        // 20200319 modify by WeiTing for M#62127 - 增加過濾已派工的設備編號或設備名稱。
                                                        if ($scope.assigned_machine == '') {
                                                            
                                                                $scope.machine_detail = data.machine_statistcs_list;

                                                        } else {
                                                                var machine_detail_filter = [];
                                                                data.machine_statistcs_list.forEach(function (item) {
                                                                        if (item.machine_no.indexOf($scope.assigned_machine) != -1
                                                                                || item.machine_name.indexOf($scope.assigned_machine) != -1) {
                                                                                machine_detail_filter.push(item);
                                                                        }
                                                                });
                                                                $scope.machine_detail = machine_detail_filter;
                                                        };

                                                        if ($scope.machine_detail.length == 0) {
                                                                if (content.machine_statistics_condition.wo_no == ''
                                                                        && content.machine_statistics_condition.plot_no == '') {
                                                                        errorMsg += $filter('translate')('A02.msg.A01first') + '<br>';
                                                                } else {
                                                                        errorMsg += $filter('translate')('common.msg.no_data') + '<br>';
                                                                }
                                                                $scope.pageInfo.totlePage = 1;
                                                        } else {
                                                                //算出機台總筆數
                                                                $scope.pageInfo.totlePage = Math.ceil($scope.machine_detail.length / $scope.pageInfo.perPageRow);
                                                        }
                                                }

                                                // dispatched_list 已派列表
                                                if (content.return_type.charAt(3) === '1') {
                                                        // 初始化已派列表
                                                        if (!$scope.dashboard.dispatched.templateUrl) {
                                                                $timeout(() => {
                                                                        $scope.dashboard.dispatched.templateUrl = 'module/moduleA/program/A08/A08_dispatched.html';
                                                                })
                                                        }

                                                        // 20200319 modify by WeiTing for M#62127 - 增加過濾已派工的設備編號或設備名稱。
                                                        if ($scope.assigned_machine == '') {
                                                               $scope.machine_detail = data.machine_statistcs_list;

                                                              
                                                        } else {
                                                                var machine_detail_filter = [];
                                                                data.machine_statistcs_list.forEach(function (item) {
                                                                        if (item.machine_no.indexOf($scope.assigned_machine) != -1
                                                                                || item.machine_name.indexOf($scope.assigned_machine) != -1) {
                                                                                machine_detail_filter.push(item);
                                                                        }
                                                                });
                                                                $scope.machine_detail = machine_detail_filter;
                                                        };

                                                        if ($scope.machine_detail.length == 0) {
                                                                if (content.dispatched_condition.wo_no == ''
                                                                        && content.dispatched_condition.plot_no == '') {
                                                                        errorMsg += $filter('translate')('A02.msg.A01first') + '<br>';
                                                                } else {
                                                                        errorMsg += $filter('translate')('common.msg.no_data') + '<br>';
                                                                }
                                                                $scope.pageInfo.totlePage = 1;
                                                        } else {
                                                                //算出機台總筆數
                                                                $scope.pageInfo.totlePage = Math.ceil($scope.machine_detail.length / $scope.pageInfo.perPageRow);
                                                        }
                                                }

                                                if (errorMsg) {
                                                        $scope.$root.showAlert(errorMsg);
                                                }

                                                if (typeof feedback === 'function') {
                                                        feedback();
                                                }

                                                EquipmentSortAction();
                                        }
                                });
                        }

                        // 展示excel已派工
                         $scope.showExeclTable = function (){
                                search({ return_type: '0200' },function(){
                                      
                                       $scope.main_event = MainPageEvent();
                                       var firstInput =1;

                                       if($scope.list.length>0 && $scope.list[0].hasOwnProperty("lst_ORM_PatchPeriodModel")){
                                          updateResult($scope.list[0].lst_ORM_PatchPeriodModel,$scope.list,firstInput);
                                          // 一次只能编辑一条数据

                                          $scope.list.forEach((item,index)=> {
                                                item['index'] = index;
                                                item.lst_ORM_PatchPeriodModel.forEach(flag=>{
                                                        flag['disabled'] = true;
                                                      })
                                              });
                                       }
                                });
                               
                                $scope.Mode = 'EXCEL';
                                $scope.dashboard.dispatched.templateUrl = 'module/moduleA/program/A08/A08_dispatched_excel.html';
                               
                                $scope.pageStyle = '';
                              
                              
                               
                        };

                        $scope.excelSearch = function (){
                                search({ return_type: '0200' },function(){
                                      
                                        $scope.main_event = MainPageEvent();
 
                                        if($scope.list.length>0 && $scope.list[0].hasOwnProperty("lst_ORM_PatchPeriodModel")){
                                           updateResult($scope.list[0].lst_ORM_PatchPeriodModel,$scope.list,2);
                                        }      
                                 
                                 });
                        },
                        $scope.detailRollback = function (index, detail) {
                                if ($scope.Mode != 'EditSeq') {
                                    if (detail.checked == 'Y') {
                                       
                                        $scope.selectRollback--;
                                        saveExcel(detail,index);

                                    } else if (!detail.checked) {

                                        $scope.Switch= false; // 是否可以編輯开关
                                        $scope.list.forEach((item,flag)=>{
                                           item.lst_ORM_PatchPeriodModel.forEach(param=>{
                                                if(param.disabled == false) {
                                                    if(flag != index) {
                                                        $scope.Switch = true;
                                                    }  
                                                }
                                           })
                                        })
                                        if($scope.Switch){
                                           $scope.$root.showAlert($filter('translate')('A08.There_is_data_being_edited_please_save_first'));
                                           return;
                                        }
                                        detail.checked = 'Y';
                                        $scope.selectRollback++;
                                        let currentItemTotal =0;
                                        let editTotal = 0;
                                      
                                        // detail.lst_ORM_PatchPeriodModel.forEach(item=>{
                                        //   editTotal += parseInt(item.patchNum);
                                        // });

                                         // 解除当前行，可以编辑

                                        
                                         $scope.list[index].lst_ORM_PatchPeriodModel.forEach(flag=>{
                                                 flag['disabled'] = false;
                                         });
                                              
                                      
                                        
                                    }
                                }
                            };
                        // 派工EXCEL 保存
                        function saveExcel(detail,param){

                                if(detail.undisqty<0){

                                   $scope.$root.showAlert($filter('translate')('A08.Undelivered_quantity_cannot_be_0'));

                                    return;    
                                }
                                  
                                                          
                                let lst_opno = [];
                                $scope.op_group_detail.forEach(function (item) {
                                        if (item.is_select == 'true'){
                                                lst_opno.push(item.op_no);
                                        }
                                 });
                                 let lst_CDO_need_dispatch_equipment_detail = [];
                               
                                 detail['lst_CDO_need_dispatch_equipment_period_detail'] = detail.lst_ORM_PatchPeriodModel;

                                
                                 lst_CDO_need_dispatch_equipment_detail.push(detail);
                                var  content= {
                                        lst_opno:lst_opno,
                                        lst_CDO_need_dispatch_equipment_detail:lst_CDO_need_dispatch_equipment_detail,
                                        area_no: $scope.selectareaNo,
                                        plot_no: detail.plot_no,
                                        op_no: detail.op_no,
                                        plugin: 0,
                                        dispatch_type: 2,
                                        work_end_date: $scope.conditions.pack_date_end,
                                        work_start_date: $scope.conditions.pack_date_start,
                                        machine_no: detail.machine_no,
                                        undisqty:detail.undisqty,
                                        mo_no:detail.mono 
                                                
                               }
     
                               $MMWService.sendToServer({
                                uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_period_process',
                                content:content,
                                success: function (data, response) {

                                         $scope.main_event.list.forEach(item=>{
                                            item.disabled = false;
                                         })
                                         detail.checked = undefined;

                                 //   保存成功后可以重新編輯其他
                              
                                 $scope.Switch= true; // 是否可以編輯开关
                               
                                 $scope.list.forEach((item,flag)=>{
                                        item.lst_ORM_PatchPeriodModel.forEach(param=>{
                                                param.disabled = true; 
                                        })
                                     })   
                                  


                                     search({ return_type: '0200' },function(){
                                      
                                        $scope.main_event = MainPageEvent();
                                        var firstInput =1;
 
                                        if($scope.list.length>0 && $scope.list[0].hasOwnProperty("lst_ORM_PatchPeriodModel")){
                                           updateResult($scope.list[0].lst_ORM_PatchPeriodModel,$scope.list,firstInput);
                                           // 一次只能编辑一条数据
 
                                           $scope.list.forEach((item,index)=> {
                                                 item['index'] = index;
                                                 item.lst_ORM_PatchPeriodModel.forEach(flag=>{
                                                         flag['disabled'] = true;
                                                       })
                                               });
                                        }
                                 });   
                                  $scope.$root.showToast($filter('translate')('A05.js.success'));
                                   
                                  
                                },
                                error: function (data, response) {
                                       
                                        $rootScope.showAlert(data.Message);
                                }
                            });
                         

                                  
                               
                       };
                        $scope.dateSetDispatchVolume = function(param, data,list){
                                if(!data.isedit){

                                    $rootScope.showAlert(data.editmessage);
                                    return;

                                }
                               
                               
                                // 一次只能编辑一行
                                let flag = false;
                                list.forEach((item,index)=>{
                                        if(item.disabled == true && index!= param.index) {
                                          $rootScope.showAlert($filter('translate')('A08.there_are_unsaved_edits'));
                                          flag = true;
 
                                        }
                                 });
                                 if(flag){
                                      return;  
                                 }else {
                                    param.disabled = true;
                                 }
                               
                               
                                var target = event.currentTarget;                                                             
                                angular.element(target).addClass('is-focus');
                                $calculater.open(
                                    function (num, calcDialog) {
                                           let total = 0;

                                           param.lst_ORM_PatchPeriodModel.forEach(item=>{
                                                 total += parseInt(item.qty);
                                            });
                                          
                                         
                                            if(param.undisqty - (num - data.qty)>=0){  
                                                param.undisqty =  param.undisqty - (num - data.qty);
                                            
                                          
                                            } else {
                                              param.undisqty =  param.undisqty + (data.qty- num);
                                            }
                                  
                                            data.qty = num;

                                           
                                            calcDialog.hide();
                                    },
                                    function (calcDialog) {
                                        angular.element(target).removeClass('is-focus');
                                        calcDialog.hide();
                                    },
                                    {
                                        defaultNum: "",
                                        decimal: true
                                    }
                                );
                        }
                        //未派工查詢
                        $scope.unassigned_search = function () {
                              
                                targetData = {
                                        qty: $scope.dispatch_filter.qty ? $scope.dispatch_filter.qty : 0,
                                        plot_no: $scope.dispatch_filter.plot_no,
                                        wo_no: $scope.dispatch_filter.wo_no,
                                        plot_start_time: $scope.conditions.pack_date_start,
                                        plot_end_time: $scope.conditions.pack_date_end,
                                        item_no: $scope.dispatch_filter.item_no,
                                        item_name: $scope.dispatch_filter.item_name,
                                        item_spec: $scope.dispatch_filter.item_spec,
                                        mono_date: $scope.dispatch_filter.mono_date,
                                        op_no: $scope.dispatch_filter.op_no,
                                        op_name: $scope.dispatch_filter.op_name
                                      
                                };

                                $scope.pageSetting.PageNumber = 1;
                                search({ return_type: '0100' },function(){
                                    search({ return_type: '0120' });
                                });
                        };

                        //清除未派工查詢
                        $scope.unassigned_clear = function () {
                                $scope.unassigned_wo_no = '';
                                $scope.unassigned_plot_no = '';
                                $scope.unassigned_search();
                        };

                        //已派工查詢
                        $scope.assigned_search = function () {
                                if ($scope.Mode == 'MachineExpend') {
                                        initMachineExpend($scope.selectMachine);
                                } else if ($scope.Mode == 'EXCEL') {
                                      //  search({ return_type: '0200' });
                                      search({ return_type: '0200' },function(){
                                      
                                        $scope.main_event = MainPageEvent();
 
                                        if($scope.list.length>0 && $scope.list[0].hasOwnProperty("lst_ORM_PatchPeriodModel")){
                                           updateResult($scope.list[0].lst_ORM_PatchPeriodModel,$scope.list);
                                           
                                           $scope.list.forEach((item,index)=> {
                                                 item['index'] = index;
                                                 item.lst_ORM_PatchPeriodModel.forEach(flag=>{
                                                         flag['disabled'] = true;
                                                       })
                                               });
                                        }
                                 });
                                } else {
                                        search({ return_type: '0020' });
                                }
                        };

                        //清除已派工查詢
                        $scope.assigned_clear = function () {
                                $scope.assigned_wo_no = '';
                                $scope.assigned_plot_no = '';
                                $scope.assigned_search();
                        };
                        var dis_date_separate_action = function () {
                                if ($scope.dispatched_detail && $scope.dispatched_detail.length > 0) {
                                        $scope.dispatched_detail.forEach(function (item) {
                                                if (item.dis_plot_start_time && item.dis_plot_start_time != "") {
                                                        var str_list = item.dis_plot_start_time.split(" ");
                                                        if (str_list.length >= 2) {
                                                                item.dis_start_date = str_list[0];
                                                                item.dis_start_time = str_list[1];
                                                        }
                                                }
                                                else {
                                                        item.dis_start_date = moment($scope.work_date).format('YYYY-MM-DD');
                                                        item.dis_start_time = "00:00:00";
                                                }
                                                if (item.dis_plot_end_time && item.dis_plot_end_time != "") {
                                                        var str_list = item.dis_plot_end_time.split(" ");
                                                        if (str_list.length >= 2) {
                                                                item.dis_end_date = str_list[0];
                                                                item.dis_end_time = str_list[1];
                                                        }
                                                }
                                                else {
                                                        item.dis_end_date = moment($scope.work_date).format('YYYY-MM-DD');
                                                        item.dis_end_time = "00:00:00";
                                                }
                                        });
                                }
                        }
                        $scope.time_open_set = function (event, detail, time, type) {
                                var target = event.currentTarget;
                                angular.element(target).addClass('is-focus');
                                var rule = /^\d{2}:\d{2}:\d{2}$/;
                                if (rule.test(time) == false)
                                        time = "00:00:00";
                                $calculater.open(function (timeDisplay, dialog) {
                                        angular.element(target).removeClass('is-focus');
                                        var hour = timeDisplay.hour, min = timeDisplay.minute, sec = timeDisplay.second;

                                        var time_str = hour + ":" + min + ":" + sec;
                                        if ((0 <= (+hour) && (+hour) < 24) &&
                                                (0 <= (+min) && (+min) < 60) &&
                                                (0 <= (+sec) && (+sec) < 60) && rule.test(time_str)) {
                                                var content = {};
                                                var time_check = true;
                                                content.need_dispatch_plot_detail = [];
                                                if (type == 4) {
                                                        detail.dis_start_time = time_str;
                                                        detail.dis_time = detail.dis_start_date + " " + time_str;
                                                        content.work_mode = "4";
                                                }
                                                else if (type == 5) {
                                                        detail.dis_time = detail.disp_end_date + " " + time_str;
                                                        content.work_mode = "5";
                                                        if (Date.parse(detail.dis_plot_start_time) > Date.parse(detail.dis_time))
                                                                time_check = false;
                                                        if (time_check)
                                                                detail.disp_end_time = time_str;
                                                }
                                                if (time_check) {
                                                        content.need_dispatch_plot_detail.push({
                                                                plot_no: detail.plot_no,
                                                                op_no: detail.op_no,
                                                                qty: detail.plot_qty,
                                                                mo_no: detail.mo_no,
                                                                machine_no: $scope.selectMachine.machine_no,
                                                                plot_start_time: detail.plot_start_time,
                                                                plot_end_time: detail.plot_end_time,
                                                                dis_time: detail.dis_time
                                                        });
                                                        content.dispatch_to = [];
                                                        content.with_draw_mode = "0";
                                                        content.dispatch_day = moment($scope.work_date).format('YYYY-MM-DD');
                                                        $MMWService.sendToServer({
                                                                uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_process',
                                                                content: content,
                                                                success: function (data) {
                                                                        search({ return_type: '110' }, function () {
                                                                                $scope.$root.showToast($filter('translate')('A05.js.success'));
                                                                                $scope.Mode = 'MachineExpend';
                                                                                var machine = $filter('filter')($scope.machine_detail, { machine_no: $scope.selectMachine.machine_no });
                                                                                if (machine != undefined && machine.length > 0) {
                                                                                        $scope.selectMachine = machine[0];
                                                                                }
                                                                                initMachineExpend($scope.selectMachine);
                                                                        });
                                                                }
                                                        });
                                                }
                                                else
                                                        $scope.$root.showAlert($filter('translate')('A02.alert.time_error_msg'));
                                                //console.log(content);

                                                angular.element(target).removeClass('is-focus');
                                                dialog.hide();
                                        } else {
                                                if ($scope.$root.showAlert)
                                                        $scope.$root.showAlert($filter('translate')('common.msg.time_format_error'));
                                        }
                                },
                                        function (dialog) {
                                                angular.element(target).removeClass('is-focus');
                                                dialog.hide();
                                        },
                                        {
                                                type: "date",
                                                defaultNum: time,
                                                title: $filter('translate')('common.msg.select_time'),
                                                decimal: false
                                        });
                        };

                       
                        //選擇區域
                        $scope.loadAreaList = function () {

                                // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
                                if ($scope.area_detail.length == 0) {
                                        var msg = $filter('translate')('A02.alert.msg2');
                                        $scope.$root.showConfirm(msg, function (dialog) {
                                                dialog.hide();
                                                $scope.loadMyFavorites();

                                        });
                                        return;
                                }

                                $scope.$root.showQueryList({
                                        key: 'page_no',
                                        header: [
                                                { label: $filter('translate')('common.queryList.area_c'), code: 'page_no' },
                                                { label: $filter('translate')('common.queryList.area_n'), code: 'page_name' }
                                        ],
                                        query: function (conditions, feedback) {
                                                feedback($scope.area_detail);
                                        },
                                        selectCode: $scope.selectareaNo || '',
                                        confirm: function (selectItem, dialog) {
                                                //  页码初始化
                                                $scope.pageSetting.PageNumber = 1;
                                                $scope.selectareaNo = selectItem.page_no;
                                                $scope.selectareaName = selectItem.page_no + ' (' + selectItem.page_name + ')';
                                                $scope.op_group_detail = [];
                                                $scope.isLine = selectItem.area_type || '0';
                                                dialog.hide();



                                                 // 获取默认生产批状态

                                                var LotState = JSON.parse(localStorage.getItem($scope.selectareaNo));
                                                                        
                                        
                                                if (LotState){
                                                $scope.initPlotNoStatus = LotState.label;

                                                $scope.project_status_code = LotState.code;
                                                }

                                                // 先查op_list 再查 undispatched_list跟machine_statistcs_list
                                                search({ return_type: '1000' }, function () {
                                                        search({ return_type: '0120' });
                                                });
                                        }
                                });
                        };
                      
                        //選擇作業站
                        $scope.loadWorkStationList = function () {
                                const content = {
                                        area_no: $scope.selectareaNo,
                                        return_type: "1000"
                                };
                                $MMWService.sendToServer({
                                        uri: 'ServicesSTD.Module_WIP.dispatch_area_info_new_get',
                                        content: content,
                                        success: function (data) {
                                                if (data && data.op_list) {
                                                        $scope.op_list = data.op_list
                                                }
                                                $scope.$root.showQueryList({
                                                        mode: 'M',
                                                        key: 'op_no',
                                                        header: [
                                                                { label: $filter('translate')('common.queryList.op_c'), code: 'op_no' },
                                                                { label: $filter('translate')('common.queryList.op_n'), code: 'op_name' }
                                                        ],
                                                        query: function (conditions, feedback) {
                                                                feedback($scope.op_list);
                                                        },
                                                        selectKey: { key: 'is_select', true: 'true', false: 'false' },
                                                        confirm: function (selectItem, dialog) {
                                                                // 工艺 
                                                               $scope.pluginType = selectItem.length>0? selectItem[0].plugin:'';

                                                                //  页码初始化
                                                                $scope.pageSetting.PageNumber = 1;
                                                                // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
                                                                var content = {
                                                                        master_no: $scope.selectareaNo,
                                                                        master_type: 8,
                                                                        favourite_user_opno: [],
                                                                        user_no: config.cache.account // 用户编号
                                                                };
                                                                var selectWorkStationName = '';
                                                                selectItem.forEach(function (item) {
                                                                        if (item.is_select == 'true') {
                                                                                // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
                                                                                content.favourite_user_opno.push({ op_no: item.op_no });

                                                                                selectWorkStationName += item.op_name + ' \\ ';
                                                                        }
                                                                });
                                                                selectWorkStationName = selectWorkStationName.substring(0, selectWorkStationName.length - 3);

                                                                $MMWService.sendToServer({
                                                                        uri: 'ServicesSTD.Module_SYS.favourite_machine_process',
                                                                        content: content,
                                                                        success: function (data) {
                                                                                $scope.selectWorkStation = '';
                                                                                $scope.selectWorkStationName = selectWorkStationName;
                                                                                dialog.hide();
                                                                                search({ return_type: '0110' });
                                                                        }
                                                                });
                                                        }
                                                });
                                        }
                                });
                        };

                        function dispatch_area_info_new_get(option, callback) {
                                let content = angular.merge(
                                        {
                                                area_no: $scope.selectareaNo,
                                                lst_opno: [],
                                                pageSetting: $scope.pageSetting,
                                                work_date: moment($scope.work_date).format("YYYY-MM-DD"),
                                                machine_statistics_condition: {
                                                        wo_no: $scope.unassigned_wo_no || "",
                                                        plot_no: $scope.unassigned_plot_no || "",
                                                },
                                                dispatched_condition: {
                                                        wo_no: $scope.assigned_wo_no || "",
                                                        plot_no: $scope.assigned_plot_no || "",
                                                },
                                                undispatched_condition: {
                                                        wo_no: "",
                                                        plot_no: "",
                                                },
                                        },
                                        option
                                );
                                $MMWService.sendToServer({
                                        uri: 'ServicesSTD.Module_WIP.dispatch_area_info_new_get',
                                        content: content,
                                        success: function (data) {
                                                if (typeof callback === 'function') {
                                                        callback(data);
                                                }
                                        }
                                });
                        }

                        $scope.changeDate = function () {
                           $datePicker.open($scope.work_date,
                                function (dialog) {
                                        $scope.work_date = dialog.datePacker.pickDate;
                                        dialog.hide();
                                        if ($scope.Mode == 'MachineExpend') {
                                                initMachineExpend($scope.selectMachine);
                                        } else {
                                                search({ return_type: '0110' });
                                        }
                            },
                            function (dialog) {
                                 dialog.hide();
                          }, {});
                        };
                        $scope.startDateChange = function () {
                           $datePicker.open($scope.conditions.pack_date_start,
                              function (dialog) {
                                 $scope.conditions.pack_date_start = moment(dialog.datePacker.pickDate).format('YYYY-MM-DD');
                                 $scope.conditions.pack_date_end = moment(dialog.datePacker.pickDate).add(6, 'd').format('YYYY-MM-DD');
                                 dialog.hide();
                                 search({ return_type: '0020' });
                                
                            },function (dialog) {
                              dialog.hide();
                            }, {});

                        };

                        $scope.endDateChange = function () {
                         $datePicker.open($scope.conditions.pack_date_end,
                             function (dialog) {
                                $scope.conditions.pack_date_end = moment(dialog.datePacker.pickDate).format('YYYY-MM-DD');
                                $scope.conditions.pack_date_start = moment(dialog.datePacker.pickDate).subtract(6, 'd').format('YYYY-MM-DD');
                                dialog.hide();
                                search({ return_type: '0020' });

                            },
                            function (dialog) {
                              dialog.hide();
                            }, {});


                        };
                        $scope.prevDate = function () {
                                // 页面初始化
                                $scope.pageSetting.PageNumber = 1;
                                $scope.work_date = moment($scope.work_date).add(-1, 'd').toDate();
                                if ($scope.Mode == 'MachineExpend') {
                                        initMachineExpend($scope.selectMachine);
                                } else {
                                        search({ return_type: '0110' });
                                }

                        };

                        $scope.nextDate = function () {
                                // 页面初始化
                                $scope.pageSetting.PageNumber = 1;
                                $scope.work_date = moment($scope.work_date).add(1, 'd').toDate();
                                if ($scope.Mode == 'MachineExpend') {
                                        initMachineExpend($scope.selectMachine);
                                } else {
                                        search({ return_type: '0110' });
                                }

                        };

                        // 20230911 modify by Alan for #136071: 增加跨頁選中功能
                        $scope.itemSelect = function (index, work) {
                                // 檢查勾選的任務是否已經在已選派工列表中
                                let targetIndex = dispatch_detail_checked.findIndex(temp => temp.plot_no == work.plot_no && temp.op_no == work.op_no);
                                $scope.pageStyle = 'EXCEL';
                                $scope.unDispatchItem = work; 
                                $scope.plot_no = work.plot_no;
                                if (work.status == '0') {
                                        // 此任務在智派工納入派工，不可重複勾選！
                                        return $scope.$root.showAlert($filter('translate')('A02.msg.sjds_dispatch_can_not_select'));
                                }
                                if (work.checked == 'Y') {
                                        work.checked = undefined;
                                        $scope.select_all_bool = false;
                                        if (targetIndex != -1) {
                                                dispatch_detail_checked.splice(targetIndex, 1);
                                        }
                                } else if (!work.checked) {
                                        work.checked = 'Y';
                                        if (targetIndex == -1) {
                                                // 保存目前頁數，提供後續比對數據異動
                                                let temp = angular.merge({}, work, { _page: $scope.pageSetting.PageNumber});
                                                dispatch_detail_checked.push(temp);
                                        }
                                }

                                // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
                                if (dispatch_detail_checked.length == 0) {
                                        $scope.Mode = '';
                                        $scope.showMode = 'query';
                                } else {
                                        $scope.Mode = 'EditSendWork';
                                        $scope.showMode = 'preview'
                                }

                                EquipmentSortAction();
                        };

                        // 20230911 modify by Alan for #136071: 增加跨頁選中功能
                        $scope.itemAllAction = function () {

                                if ($scope.dispatch_detail.length <= 0)
                                        return;
                                for (var i in $scope.dispatch_detail) {
                                        // 檢查勾選的任務是否已經在已選派工列表中
                                        let targetIndex = dispatch_detail_checked.findIndex(temp => temp.plot_no == $scope.dispatch_detail[i].plot_no && temp.op_no == $scope.dispatch_detail[i].op_no);
                                        if ($scope.select_all_bool) {
                                                $scope.dispatch_detail[i].checked = '';
                                                if (targetIndex != -1) {
                                                        dispatch_detail_checked.splice(targetIndex, 1);
                                                }
                                        }
                                        else {
                                                // 狀態 0 代表任務在智派工納入派工，不可勾選！
                                                if ($scope.dispatch_detail[i].status == '0') {
                                                        $scope.dispatch_detail[i].checked = '';
                                                }
                                                else {
                                                        $scope.dispatch_detail[i].checked = 'Y';
                                                        if (targetIndex == -1) {
                                                                // 保存目前頁數，提供後續比對數據異動
                                                                let temp = angular.merge({}, $scope.dispatch_detail[i], { _page: $scope.pageSetting.PageNumber});
                                                                dispatch_detail_checked.push(temp);
                                                        }
                                                }
                                        }
                                }

                                $scope.select_all_bool = !$scope.select_all_bool; 
                                // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
                                if (dispatch_detail_checked.length == 0) {
                                        $scope.showMode = "query"
                                        $scope.Mode = '';
                                }
                                else {
                                        $scope.showMode = "preview"
                                        $scope.Mode = 'EditSendWork';
                                }
                        };

                        // 20230911 modify by Alan for #136071: 增加跨頁選中功能
                        $scope.SelectedInfo = {
                                // 本页选中：　0
                                current() {
                                        let amount = $filter('filter')($scope.dispatch_detail, { checked: 'Y' }).length;
                                        return $filter('translate')('A08.selected_info.current', { amount });
                                },
                                // 合计选中：　0
                                total() {
                                        let amount = $filter('filter')(dispatch_detail_checked, { checked: 'Y' }).length;
                                        return $filter('translate')('A08.selected_info.total', { amount });
                                },
                        };

                        // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
                        var pdf_url;
                        $scope.preview = function () {
                                var plot_detail = [];
                                if ($scope.Mode == 'Rollback') {
                                        $scope.dispatched_detail.forEach(function (item) {
                                                if (item.checked == 'Y') {
                                                        var info = {
                                                                plot_no: item.plot_no,
                                                                plot_qty: item.qty
                                                        }
                                                        plot_detail.push(info);
                                                }
                                        });
                                } else {
                                        var dispach_detail = $filter('filter')($scope.dispatch_detail, $scope.dispatch_filter);
                                        dispach_detail.forEach(function (detail, index) {
                                                if (detail.checked == 'Y') {
                                                        var info = {
                                                                plot_no: detail.plot_no,
                                                                plot_qty: detail.qty
                                                        }
                                                        plot_detail.push(info);
                                                }
                                        });
                                }

                                $MMWService.sendToServer({
                                        uri: 'ServicesSTD.Module_WIP.runcard_pdf_get',
                                        content: {
                                                course: ($scope.show_history ? '1' : '0'),
                                                plot_detail: plot_detail
                                        },
                                        success: function (data) {

                                                for (var i = 0; i < plot_detail.length; i++) {
                                                        $scope.printList.push({
                                                                printNo: plot_detail[i].plot_no,
                                                                printType: '1' // 1: 流程卡打印 + 生產批開立; 3: 條碼標籤打印(補印); 4: 外包單 - 出貨打印; 5. 叫修作業;
                                                        });
                                                }

                                                pdf_url = data.runcard_pdf_get[0].url_pdf;
                                                if (pdf_url.indexOf('http://') == -1) {
                                                        pdf_url = 'http://' + config.server.ip + ':' + config.server.port + pdf_url;
                                                }
                                                if (config.setting.outsidePDF == 'Y') {
                                                        var fs = window.nodeRequire('fs'), RuncardPath;
                                                        try {
                                                                // 20240321 modify by Alan for#159805 : electron升級後，兼容新舊版本
                                                                const remote = window.nodeRequire('electron').remote || window.nodeRequire('@electron/remote');
                                                                RuncardPath = remote.app.getAppPath();
                                                        } catch (e) {
                                                                RuncardPath = window.nodeRequire('path').dirname(process.execPath) + '\\package.nw';
                                                        }
                                                        RuncardPath += '\\www\\Runcard';
                                                        if (!fs.existsSync(RuncardPath)) {
                                                                fs.mkdirSync(RuncardPath);
                                                        }

                                                        // 20240222 add by Alan for#158151 : 清除Runcard目錄下未開啟的舊檔案
                                                        // 20240408 modify by Alan for#139948 : 改成同步讀取，避免刪除檔案後立即列印造成找不到檔案
                                                        fs.readdirSync(RuncardPath, (err, files) => {
                                                                if (err) {
                                                                        console.log(err);
                                                                }
                                                                //listing all files using forEach
                                                                files.forEach((file) => {
                                                                        // Do whatever you want to do with the file
                                                                        fs.unlink(RuncardPath + '/' + file, (err) => {
                                                                                if (err) {
                                                                                        console.debug(err);
                                                                                }
                                                                        })
                                                                });
                                                        })

                                                        // 20240222 add by Alan for#158151 : 增加時間戳記，避免檔名重複造成檔案開啟時無法寫入
                                                        let pdfPath = `${RuncardPath}/RuncardPreview_${Date.now()}.pdf`;
                                                        $scope.$root.downloadFile(pdf_url, pdfPath, function (dist_path) {
                                                                // 20230807 modify by Alan for#130433 : electron升版後，shell.openItem改成shell.openPath
                                                                const { shell } = window.nodeRequire('electron');
                                                                shell.openItem ? shell.openItem(dist_path) : shell.openPath(dist_path);
                                                        });
                                                } else {
                                                        showPDFViewer(pdf_url);
                                                }
                                        }
                                });
                        };

                        // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
                        function showPDFViewer(pdf_url) {
                                try {
                                        window.nodeRequire('nw.gui').Window.open(pdf_url, {
                                                title: 'PDF Viewer',
                                                show: false,
                                                icon: 'icon/icon.png',
                                                focus: true
                                        }, function (win) {
                                                win.on('loaded', function () {
                                                        win.show();
                                                        win.print();
                                                });
                                        });
                                } catch (e) {
                                        $scope.showMode = 'print';
                                        document.getElementById('kmi-pdf-panel').src = 'JSplugins/pdfjs/web/viewer.html?file=' + pdf_url + '&openfile=false&viewbookmark=false&printfile=false&download=false#zoom=page-width';
                                }
                        }
                        // 20230303 modify by shiwl for M#117692: 派工作业 - 增加流程卡列印
                        $scope.ClickDoFlag = function () {
                                if ($scope.do_flag == 0) {
                                  $scope.do_flag = 1;
                                } else {
                                  $scope.do_flag = 0;
                                }
                        };
                        // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
                        $scope.print = function () {
                                if (window.nodeRequire || window.cordova) {
                                        $scope.$root.showLoading();
                                        // 20231213 modify by wenwei for M#152621: 6.1标签打印改写搬迁
                                        $scope.$root.multiPrint([pdf_url], ()=>{
                                                printWiplogProcess(); // 列印完成後，需把列印詳情回送給後台做記錄
                                                $scope.$root.hideLoading();
                                                $scope.$root.showToast($filter('translate')('common.msg.success'));
                                        })
                                } else {
                                        window.frames['kmi-pdf-panel'].pdf_print();
                                }
                                /*
                                if(config.setting.printSetting){
                                    $PrintSetting.init({
                                        callback:function(settings){
                                            window.frames['kmi-pdf-panel'].pdf_print(settings);
                                        }
                                    });
                                } else {
                                    window.frames['kmi-pdf-panel'].pdf_print();
                                }
                                */
                        };

                        // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
                        $scope.download = function () {
                                window.frames['kmi-pdf-panel'].pdf_download();
                        };
                     
                        // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
                        $scope.cancel = function () {
                                if ($scope.Mode == 'Rollback') {
                                        $scope.showMode = 'query';
                                } else {
                                        $scope.showMode = 'preview';
                                }
                                document.getElementById('kmi-pdf-panel').src = '';
                                $scope.printList = [];
                        };

                        // 20201216 ADD FOR M#83236-1
                        // 列印完成後，需把列印詳情回送給後台做記錄
                        function printWiplogProcess() {
                                $MMWService.sendToServer({
                                        uri: 'ServicesSTD.Module_SN.print_wiplog_process',
                                        content: {
                                                printList: $scope.printList
                                        },
                                        success: function () {
                                                $scope.printList = [];
                                        }
                                });
                        }
                        $scope.excelSave = function (){
                           
                            var content = $scope.machine_detail;
                            $MMWService.sendToServer({
                                uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_period_process',
                                content:content,
                                success: function (data, response) {
                                   
                                        $rootScope.showAlert("保存成功");
                                   
                                }
                            });
                        };
                        $scope.pageInfo = {
                                nowPage: 1,
                                totlePage: 1,
                                perPage: 10,
                                perPageRow: 4
                        };

                        // 20230620 modify by Alan for #132192: 修正設備狀態
                        $scope.machineStatus = function (status) {
                                return 'status_' + convertMachineStatus(status);
                        };

                        $scope.machineStatusDisplay = function (status) {
                                const key = 'common.machine.status.' + convertMachineStatus(status);
                                return $filter('translate')(key).substring(0, 1);
                        };

                        function convertMachineStatus(status) {
                                const convertMap = {
                                        '3': '6',
                                        '4': '3',
                                        '6': '7',
                                        '7': '4'
                                }

                                return convertMap[status] || status.toString();
                        }

                        $scope.selectMachine = undefined;
                        // 设备日期转化周
                        $scope.getWeek = function (date) {
                               //  let weeks = ['日', '一', '二', '三', '四', '五', '六'];

                                let weeks = [
                                        $filter('translate')('A08.Sunday'), 
                                        $filter('translate')('A08.Monday'),
                                        $filter('translate')('A08.Tuesday'), 
                                        $filter('translate')('A08.Wednesday'),
                                        $filter('translate')('A08.Thursday'), 
                                        $filter('translate')('A08.Friday'),
                                        $filter('translate')('A08.Saturday'), 
                                       
                                ]
                              
                                let day = new Date(date || new Date()).getDay();
                                if( date ==  moment(new Date()).format('YYYY-MM-DD')) {
                                   return $filter('translate')('A08.today');
                                } else {
                                   return weeks[day];
                                }
                               

                        };
                        // 改变已派工高度 // 20230523 modify by 15016 for M#0132192: 多日派工功能优化（设备显示、派工校验）
                        $scope.expandPage = true;
                        $scope.deviceHeight = true;

                        $scope.changeHeight = function () {
                                $scope.expandPage = !$scope.expandPage;
                                $scope.deviceHeight = !$scope.deviceHeight;
                        };

                        // 20230615 modify by 15016 for M#0132192: 多日派工功能优化（设备显示、派工校验）
                        $scope.cellStyle = function (item) {
                                if ((+item.machine_load) <= 60) { //绿色
                                return { 'border': '3px solid #65bd85' };
                                } else if ((+item.machine_load) <= 80) { //橙色
                                return { 'border': '3px solid #FFB037' };
                                } else { //红色
                                return { 'border': '3px solid #A30014' };
                                }
                                return {};
                        }
                        
                        $scope.getMachineList = function (param) {
                                // var start = ($scope.pageInfo.nowPage - 1) * $scope.pageInfo.perPageRow;
                                // var end = ($scope.pageInfo.nowPage) * $scope.pageInfo.perPageRow;
                                return $scope.machine_detail;
                        };

                        $scope.prevPage = function () {
                                if ($scope.pageInfo.nowPage > 1)
                                        $scope.pageInfo.nowPage--;
                        };

                        $scope.nextPage = function () {
                                if ($scope.pageInfo.nowPage < $scope.pageInfo.totlePage)
                                        $scope.pageInfo.nowPage++;
                        };

                        //展開機台上的已派工清單
                        function expendMachine(index, item, items) {
                           // $rootScope.changeProgram('A10',item,items);
                             $scope.$root.changeProgram('A10', {data: {
                                machine: item,
                                machine2:items,
                                assigned_wo_no: $scope.assigned_wo_no,
                                assigned_plot_no: $scope.assigned_plot_no,
                                assigned_machine: $scope.assigned_machine,
                                selectareaNo:  $scope.selectareaNo,
                               // selectWorkStationName: $scope.selectWorkStationName,
                               // lst_opno: $scope.lst_opno,
                                lst_opno: $scope.op_group_detail

                               
                            }});
                        }

                        var sortablList, dispatched_detail_backup;
                        function initMachineExpend(item) {

                                // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
                                if ($scope.area_detail.length == 0) {
                                        var msg = $filter('translate')('A02.alert.msg2');
                                        $scope.$root.showConfirm(msg, function (dialog) {
                                                dialog.hide();
                                                $scope.loadMyFavorites();

                                        });
                                        return;
                                }
                                const content = {
                                        return_type: '0001',
                                        area_no: $scope.selectareaNo,
                                        lst_opno: $scope.op_group_detail.map(item =>  item.op_no),
                                        work_date: moment($scope.work_date).format("YYYY-MM-DD"),
                                        dispatched_condition: {
                                                machine_no: item.machine_no,
                                                wo_no: $scope.assigned_wo_no || '',
                                                plot_no: $scope.assigned_plot_no || ''
                                        },
                                        machine_statistics_condition: {
                                                wo_no: '',
                                                plot_no: ''
                                        },
                                }
                                // search({ return_type: '0001'});
                                dispatch_area_info_new_get(content, function (data) {

                                        // 初始化已派列表
                                        if (!$scope.dashboard.dispatched.templateUrl) {
                                                $timeout(() => {
                                                        $scope.dashboard.dispatched.templateUrl = 'module/moduleA/program/A08/A08_dispatched.html';
                                                })
                                        }
                                        let dispatched_detail = data.dispatched_list;
                                        if (sortablList) {
                                                sortablList.destroy();
                                                sortablList = undefined;
                                                dispatched_detail_backup = undefined;
                                                $scope.dispatched_detail = [];
                                        }
                                        dispatched_detail_backup = dispatched_detail.slice();
                                        //20220929 modify by wangzy for 0119508: 华禹彩印：派工作业处部分已派工数据无法调整顺序
                                        var list = [];
                                        list = list.concat(dispatched_detail.filter(item => item.states != '0'));
                                        list = list.concat(dispatched_detail.filter(item => item.states == '0'));
                                        // 20221104 modify by Alan for #118298: 可能是測試留下來的代碼，註解以避免錯誤
                                        // list.forEach(item => item.states = '0')
                                        $scope.dispatched_detail = list;
                                        dis_date_separate_action();
                                        if (content.dispatched_condition.wo_no == '' && content.dispatched_condition.plot_no == '') {
                                                $scope.is_lock_sort = false;
                                        } else {
                                                $scope.is_lock_sort = true;
                                        }

                                        if (!$scope.is_lock_sort) {
                                                $timeout(function () {
                                                        sortablList = Sortable.create(document.getElementById('sortablelist'), {
                                                                ghostClass: 'ghost',
                                                                filter: '.undragable',
                                                                handle: '.sortable-btn',
                                                                onEnd: function (evt) {
                                                                        if ($scope.Mode != 'EditSeq')
                                                                                $scope.Mode = 'EditSeq';
                                                                        //console.log(evt);
                                                                        if (item.dispatch_size === undefined) {
                                                                                item.dispatch_size = 0
                                                                        }
                                                                        var newIndex = evt.newIndex + item.dispatch_size;
                                                                        var oldIndex = evt.oldIndex + item.dispatch_size;
                                                                        var chooseItem = $scope.dispatched_detail.splice(oldIndex, 1)[0];
                                                                        //20181218 add by Dustdusk for M#: 防止沒抓到還塞進陣列內
                                                                        if (chooseItem != undefined) {
                                                                                $scope.dispatched_detail.splice(newIndex, 0, chooseItem);
                                                                                $scope.$apply();
                                                                        }
                                                                }
                                                        });
                                                });
                                        } else {
                                                $scope.$root.showToast($filter('translate')('A02.msg.cant_sort'));
                                        }
                                })

                        }

                        var MachineListMode = '', dispatchItem, machineList;
                        $scope.itemSendwork = function (index, item) {
                                if (item.status == '0') {
                                        // 此任務在智派工納入派工，不可重複勾選！
                                        return $scope.$root.showAlert($filter('translate')('A02.msg.sjds_dispatch_can_not_select'));
                                }
                                if ($scope.Mode != 'EditSendWork') {
                                        var feedback = function (data) {
                                                MachineListMode = '1';//表示派工
                                                dispatchItem = item;
                                                machineList = EquipmentSortForDialogAction(item, data);
                                                $mdDialog.dialog(
                                                        'module/moduleA/program/A02/A2_MachineList.tmp.html',
                                                        MachineListController
                                                );
                                        };
                                        if ($scope.isLine == '1')
                                                getLineMachineList(item.plot_no, item.op_no, $scope.work_date, feedback);
                                        else
                                                getMachineList($scope.work_date, feedback);
                                }
                        };

                        $scope.itemAccessory = function (item) {
                                $scope.acc_detail = [];
                                if (!item.accessory_no) {
                                        $scope.$root.showAlert($filter('translate')('A02.msg.no_accessory_no'));
                                        return;
                                }
                                $scope.acc_detail = item.product_acc_detail;
                                $mdDialog.dialog(
                                        'module/moduleA/program/A02/A2_AccList.tmp.html',
                                        AccDetailController
                                );
                        };

                        function AccDetailController(dialog) {
                                return {
                                        product_acc_detail: $scope.acc_detail,
                                        PageConfig: { page: 0, page_count: 25 },
                                        order_by_mode: { name: "", sort: false },
                                        dispatch_filter: {},
                                        orderbychange: function (mode) {
                                                if (dialog.order_by_mode.name != mode) {
                                                        dialog.order_by_mode.name = mode;
                                                        dialog.order_by_mode.sort = false;
                                                }
                                                else {
                                                        if (dialog.order_by_mode.sort)
                                                                dialog.order_by_mode.sort = false;
                                                        else
                                                                dialog.order_by_mode.sort = true;
                                                }

                                        },
                                        getPages: function (list, PageConfig,filterItem) {
                                                if (list) {
                                                        if (dialog.order_by_mode.name != "")
                                                                list = $filter('orderBy')(list, dialog.order_by_mode.name, dialog.order_by_mode.sort);
                                                        var temp_list = list.filter(function (item, index, array) {
                                                                var isOK = true,
                                                                        keys = Object.keys(filterItem);
                                                                for (var i = 0; i < keys.length; i++) {
                                                                        var key = keys[i];
                                                                        if (isOK && item[key] != null && filterItem[key] && filterItem[key] != '') {
                                                                                if (item[key].toString().indexOf(filterItem[key]) == -1) {
                                                                                        isOK = false;
                                                                                        break;
                                                                                }
                                                                        }
                                                                }
                                                                return isOK;
                                                        });
                                                        if (PageConfig) {
                                                                if (temp_list.length != 0) {
                                                                        PageConfig.total_page = Math.ceil(temp_list.length / PageConfig.page_count);

                                                                        if (PageConfig.page >= PageConfig.total_page) {
                                                                                PageConfig.page = 0;
                                                                        }
                                                                        var index = PageConfig.page * PageConfig.page_count;
                                                                        return temp_list.slice(index, index + PageConfig.page_count);
                                                                } else {
                                                                        PageConfig.total_page = 1;
                                                                        PageConfig.page = 0;
                                                                }
                                                        } else {
                                                                return temp_list;
                                                        }
                                                } else {

                                                        return list;
                                                }
                                        },
                                        back: function () {
                                                dialog.hide();
                                        }
                                }
                        }

                        function MachineListController(dialog) {
                                return {
                                        isLine: $scope.isLine,
                                        MachineListMode: MachineListMode,
                                        work_date: $scope.work_date,
                                        dispatchItem: dispatchItem,
                                        machineList: machineList,
                                        mlightColor: $scope.mlightColor,
                                        order_by_mode: { name: "", sort: false },
                                        dispatch_filter: {},
                                        orderbychange: function (mode) {
                                                if (dialog.order_by_mode.name != mode) {
                                                        dialog.order_by_mode.name = mode;
                                                        dialog.order_by_mode.sort = false;
                                                }
                                                else {
                                                        if (dialog.order_by_mode.sort)
                                                                dialog.order_by_mode.sort = false;
                                                        else
                                                                dialog.order_by_mode.sort = true;
                                                }

                                        },
                                        getMachineList: function (list, filterItem) {
                                                if (list) {
                                                        if (dialog.order_by_mode.name != "")
                                                                list = $filter('orderBy')(list, dialog.order_by_mode.name, dialog.order_by_mode.sort);
                                                        var temp_list = list.filter(function (item, index, array) {
                                                                var isOK = true,
                                                                        keys = Object.keys(filterItem);
                                                                for (var i = 0; i < keys.length; i++) {
                                                                        var key = keys[i];
                                                                        if (isOK && item[key] != null && filterItem[key] && filterItem[key] != '') {
                                                                                if (item[key].toString().indexOf(filterItem[key]) == -1) {
                                                                                        isOK = false;
                                                                                        break;
                                                                                }
                                                                        }
                                                                }
                                                                return isOK;
                                                        });
                                                        return temp_list;
                                                } else {
                                                        return list;
                                                }
                                        },
                                        changeDate: function () {
                                                $datePicker.open(dialog.work_date,
                                                        function (mdDialog) {
                                                                dialog.work_date = mdDialog.datePacker.pickDate;
                                                                mdDialog.hide();
                                                                var feedback = function (data) {
                                                                        dialog.machineList = data;
                                                                };
                                                                if ($scope.isLine == '1')
                                                                        getLineMachineList(dialog.dispatchItem.plot_no, dialog.dispatchItem.op_no, dialog.work_date, feedback);
                                                                else
                                                                        getMachineList(dialog.work_date, feedback);
                                                        },
                                                        function (dialog) {
                                                                dialog.hide();
                                                        }, {});
                                        },
                                        prevDate: function () {
                                                dialog.work_date = moment(dialog.work_date).add(-1, 'd').toDate();
                                                var feedback = function (data) {
                                                        dialog.machineList = data;
                                                };
                                                if ($scope.isLine == '1')
                                                        getLineMachineList(dialog.dispatchItem.plot_no, dialog.dispatchItem.op_no, dialog.work_date, feedback);
                                                else
                                                        getMachineList(dialog.work_date, feedback);
                                        },
                                        nextDate: function () {
                                                dialog.work_date = moment(dialog.work_date).add(1, 'd').toDate();
                                                var feedback = function (data) {
                                                        dialog.machineList = data;
                                                };
                                                if ($scope.isLine == '1')
                                                        getLineMachineList(dialog.dispatchItem.plot_no, dialog.dispatchItem.op_no, dialog.work_date, feedback);
                                                else
                                                        getMachineList(dialog.work_date, feedback);
                                        },
                                        back: function () {
                                                dialog.hide();
                                        },
                                        confirm: function () {
                                                if (MachineListMode == '1') {
                                                        MachineListConfirmDispatch(dialog);
                                                } else if (MachineListMode == '2') {
                                                        MachineListConfirmTransfer(dialog);
                                                }
                                                $scope.roll_back_all_bool = false;
                                        }
                                };
                        }

                        function getMachineList(work_date, feedback) {
                                var content = {
                                        dispatch_detail_condition: [{ wo_no: '', plot_no: '' }],//未派工
                                        machine_detail_condition: [{ wo_no: '', plot_no: '' }],//已派工
                                        op_no: '',
                                        area_no: $scope.selectareaNo,
                                        work_date: moment(work_date).format('YYYY-MM-DD'),
                                        return_type: '010'
                                };

                                $MMWService.sendToServer({
                                        uri: 'ServicesSTD.Module_WIP.dispatch_area_info_get',
                                        content: content,
                                        success: function (data) {
                                                //已派工
                                                if (data.machine_detail && data.machine_detail.length != 0) {
                                                        if (feedback)
                                                                feedback(data.machine_detail);
                                                } else {
                                                        $scope.$root.showAlert($filter('translate')('A02.msg.A01first'));
                                                }
                                        }
                                });
                        }

                        function getLineMachineList(plot_no, op_no, work_date, feedback) {
                                var content = {
                                        page_mode: 'dispatch_line_equipment_info_get',
                                        query_condition_info: []
                                };
                                content.query_condition_info.push({ column_name: 'A.LOTNO', query_mode: '0', value: plot_no, merge_condition_model: 'AND' });
                                content.query_condition_info.push({ column_name: 'A.OPNO', query_mode: '0', value: op_no, merge_condition_model: 'AND' });
                                content.query_condition_info.push({ column_name: 'workdate', query_mode: '0', value: moment(work_date).format('YYYYMMDD') + '000000', merge_condition_model: 'AND' });

                                $MMWService.pageNumberInfoGet(content, function (data) {
                                        //已派工
                                        if (data && data.length != 0) {
                                                data.forEach(function (machine) {
                                                        machine.used_capacity = Math.round(machine._used_capacity * 100 / 60) / 100;
                                                        machine.machine_load = Math.round(machine.used_capacity * 100 / machine.capacity);
                                                        if (machine.machine_load > 80)
                                                                machine.load_status = 'H';
                                                        else if (machine.machine_load >= 60)
                                                                machine.load_status = 'M';
                                                        else
                                                                machine.load_status = 'L';
                                                });
                                                if (feedback)
                                                        feedback(data);
                                        } else {
                                                $scope.$root.showAlert($filter('translate')('A02.msg.A01first'));
                                        }
                                });
                        }

                        //派工到多機台
                        function MachineListConfirmDispatch(dialog) {
                                var dispatchSum = 0;
                                var content = {
                                        need_dispatch_plot_detail: [dispatchItem],
                                        dispatch_to: [],
                                        work_mode: 1,
                                        dispatch_day: moment(dialog.work_date).format('YYYY-MM-DD')
                                };

                                dialog.machineList.forEach(function (machine, index) {
                                        if (machine.inputQty != undefined && machine.inputQty != 0) {
                                                content.dispatch_to.push({ machine_no: machine.machine_no, qty: machine.inputQty });
                                                dispatchSum += (+machine.inputQty);
                                        }
                                });

                                var _fn = function (request) {
                                        $MMWService.sendToServer({
                                                uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_process',
                                                content: request,
                                                success: function (data) {
                                                        if (data.dispatch_msg && data.dispatch_msg.length > 0) {
                                                                var msg = data.dispatch_msg.join("<br>")
                                                                $scope.$root.showConfirm(msg, function (confirm_dialog) {
                                                                        confirm_dialog.hide();
                                                                        enforce_dispatch_action(request, function () {
                                                                                dialog.hide();
                                                                                $scope.work_date = dialog.work_date;
                                                                                search({ return_type: '0020' }, function () {
                                                                                        $scope.$root.showToast(dispatchItem.plot_no + $filter('translate')('A02.msg.saveSuccess'));
                                                                                });
                                                                        });
                                                                });
                                                        }
                                                        else {
                                                                dialog.hide();
                                                                $scope.work_date = dialog.work_date;
                                                                search({ return_type: '0020' }, function () {
                                                                        $scope.$root.showToast(dispatchItem.plot_no + $filter('translate')('A02.msg.saveSuccess'));
                                                                });
                                                        }
                                                }
                                        });
                                };

                                if (content.dispatch_to.length == 0) {
                                        //尚未輸入派工數量
                                        $scope.$root.showAlert($filter('translate')('A02.msg.no_dispatch_qty'));
                                } else if (dispatchSum <= dispatchItem.qty) {
                                        dispatch_info_calculation_process(content, function (data) {
                                                if (data && data.suggest_detail && data.suggest_detail.length > 0) {
                                                        OpenMachineSuggestListDialog(1, content, data.suggest_detail);
                                                        dialog.hide();
                                                }
                                                else if (data && data.msg != '') {
                                                        $scope.$root.showConfirm(data.msg, function (dialogType) {
                                                                dialogType.hide();
                                                                _fn(content);
                                                        });
                                                }
                                                else {
                                                        _fn(content);
                                                };
                                        });
                                } else {
                                        $scope.$root.showAlert($filter('translate')('A02.msg.numOver') + dispatchItem.qty);
                                }
                        }

                        $scope.machineSelect = function (index, machine, items, parentIndex, event) {
                                $scope.selectMachinDate = machine.work_date;
                                $scope.need_dispatch_plot_detail = []; // 生产批选择置空
                                $scope.deviceListData = items;
                                if ($scope.Mode == 'EditSendWork') {
                                        //  itemMutiSendwork(machine);
                                        // 20230911 modify by Alan for #136071: 增加跨頁選中功能
                                        $scope.need_dispatch_plot_detail = $filter('filter')(dispatch_detail_checked, $scope.dispatch_filter);
                                       
                                        if($scope.need_dispatch_plot_detail.length <= 1){
                                               
                                                $scope.plotItem = ''; $scope.machine_no = ''; $scope.plot_no;; $scope.temp_list = "";
                                                var obj = {
                                                        area_no:$scope.selectareaNo,
                                                        plugin: $scope.pluginType, 
                                                        work_start_date:$scope.conditions.pack_date_start,
                                                        work_end_date: $scope.conditions.pack_date_end
                                                }
                                                Object.assign( $scope.unDispatchItem, obj );
                                                let lst_opno= [];
                                                $scope.op_group_detail.map(item =>{
                                                   if(item.is_select=='true'){
                                                        lst_opno.push(item.op_no)  
                                                   }
                                                } )
                                                $mdDialog.serviceDialog('A0801Service',$scope.unDispatchItem, $scope.plot_no, 'A08', items, $scope.machine_detail, parentIndex,index,$scope.unDispatchItem,lst_opno,machine,function () {  
                                                        search({ return_type: '0120' }, function () {
                                                        $scope.showMode = 'query';
                                                        $scope.Mode = '';                                                   
                                                        $scope.roll_back_all_bool = false;
                                                     });
                                                });
                                        } else {
                                               
                                              
                                                itemMutiSendwork(items);
                                        }
                                       
                                } else {
                                        expendMachine(index, machine, items);
                                }
                                
                        };

                        $scope.closeMachine = function () {
                                $scope.Mode = '';
                                $scope.selectMachine = undefined;
                                if (sortablList) {
                                        sortablList.destroy();
                                        sortablList = undefined;
                                        dispatched_detail_backup = undefined;
                                        $scope.dispatched_detail = [];
                                }
                                // 初始化页码
                                $scope.pageSetting.PageNumber = 1;
                                dispatch_area_info_new_get({ return_type: '0110' });
                        };

                        //多生產批同時派工
                        function itemMutiSendwork(machine) {
                                var content = {
                                        need_dispatch_plot_detail: [],
                                        dispatch_to: [{ machine_no: machine.machine_no}],
                                        work_mode: 1,
                                        dispatch_day: $scope.selectMachinDate
                                };
                                // 20230911 modify by Alan for #136071: 增加跨頁選中功能
                                content.need_dispatch_plot_detail = $filter('filter')(dispatch_detail_checked, $scope.dispatch_filter);
                                if (content.need_dispatch_plot_detail.length <= 0) {
                                        $scope.$root.showAlert($filter('translate')('A02.msg.no_dispatch_detail'));
                                        return;
                                }
                                if (content.need_dispatch_plot_detail.length == 1) {
                                        content.dispatch_to[0].qty = content.need_dispatch_plot_detail[0].qty;
                                }

                                var _fn = function (request) {
                                        $MMWService.sendToServer({
                                                uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_process',
                                                content: request,
                                                success: function (data) {
                                                        if (data.dispatch_msg && data.dispatch_msg.length > 0) {
                                                                var msg = data.dispatch_msg.join("<br>")
                                                                $scope.$root.showConfirm(msg, function (confirm_dialog) {
                                                                        confirm_dialog.hide();
                                                                        enforce_dispatch_action(request, function () {
                                                                                search({ return_type: '0120' }, function () {
                                                                                        $scope.$root.showToast(
                                                                                                content.need_dispatch_plot_detail.length
                                                                                                + $filter('translate')('A02.msg.sendWorkSuccess')
                                                                                                + '[' + machine.machine_no + ']');
                                                                                        $scope.Mode = '';
                                                                                        $scope.select_all_bool = false;
                                                                                        // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
                                                                                        $scope.showMode = 'query';
                                                                                });
                                                                        });
                                                                });
                                                        }
                                                        else {
                                                                search({ return_type: '0120' }, function () {
                                                                        $scope.$root.showToast(
                                                                                content.need_dispatch_plot_detail.length
                                                                                + $filter('translate')('A02.msg.sendWorkSuccess')
                                                                                + '[' + machine.machine_no + ']');
                                                                        $scope.Mode = '';
                                                                        $scope.select_all_bool = false;
                                                                        // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
                                                                        $scope.showMode = 'query';
                                                                });
                                                        }
                                                },
                                                error: function (data) {
                                                        // 20230911 modify by Alan for #136071: 後端卡控時，退出勾選狀態
                                                        $scope.$root.showAlert(data.ExceptionMessage);
                                                        $scope.Mode = '';
                                                        // 送出的數據可能已經配派掉了，所以要重新查詢
                                                        search({ return_type:'0110' })
                                                }
                                        });
                                };

                                dispatch_info_calculation_process(content, function (data) {
                                        if (data && data.suggest_detail && data.suggest_detail.length > 0) {
                                                OpenMachineSuggestListDialog(0, content, data.suggest_detail);
                                        }
                                        else if (data && data.msg != '') {
                                                $scope.$root.showConfirm(data.msg, function (dialogType) {
                                                        dialogType.hide();
                                                        _fn(content);
                                                });
                                        }
                                        else {
                                                _fn(content);
                                        };
                                });
                        };
                        //建議數量開窗 
                        //work_mode = 0 =多筆生產批派一筆設備 
                        //work_mode = 1 = 一筆生產批派多個設備
                        //submit_data = 派工原始明細
                        //suggest_detail = 派工建議明細
                        function OpenMachineSuggestListDialog(work_mode, submit_data, suggest_detail) {
                                $mdDialog.dialog(
                                        'module/moduleA/program/A02/A2_MachineList_suggest.html',
                                        function (dialog) {
                                                return {
                                                        suggest_detail: suggest_detail,
                                                        mlightColor: $scope.mlightColor,
                                                        submit_data: submit_data,
                                                        work_mode: work_mode,
                                                        order_by_mode: { name: "", sort: false },
                                                        dispatch_filter: {},
                                                        init: function () {

                                                        },
                                                        orderbychange: function (mode) {
                                                                if (dialog.order_by_mode.name != mode) {
                                                                        dialog.order_by_mode.name = mode;
                                                                        dialog.order_by_mode.sort = false;
                                                                }
                                                                else {
                                                                        if (dialog.order_by_mode.sort)
                                                                                dialog.order_by_mode.sort = false;
                                                                        else
                                                                                dialog.order_by_mode.sort = true;
                                                                }

                                                        },
                                                        getSuggestDetail: function (list, filterItem) {
                                                                if (list) {
                                                                        if (dialog.order_by_mode.name != "")
                                                                                list = $filter('orderBy')(list, dialog.order_by_mode.name, dialog.order_by_mode.sort);
                                                                        var temp_list = list.filter(function (item, index, array) {
                                                                                var isOK = true,
                                                                                        keys = Object.keys(filterItem);
                                                                                for (var i = 0; i < keys.length; i++) {
                                                                                        var key = keys[i];
                                                                                        if (isOK && item[key] != null && filterItem[key] && filterItem[key] != '') {
                                                                                                if (item[key].toString().indexOf(filterItem[key]) == -1) {
                                                                                                        isOK = false;
                                                                                                        break;
                                                                                                }
                                                                                        }
                                                                                }
                                                                                return isOK;
                                                                        });
                                                                        return temp_list;
                                                                } else {
                                                                        return list;
                                                                }
                                                        },
                                                        checkSuggestQty: function (event, item) {
                                                                var target = event.currentTarget;
                                                                angular.element(target).addClass('is-focus');
                                                                $calculater.open(
                                                                        function (num, dialog) {
                                                                                angular.element(target).removeClass('is-focus');
                                                                                dialog.hide();
                                                                                if ((+num) >= 0 && (+num) <= (+item.limit_qty))
                                                                                        item.sug_qty = num;
                                                                                else
                                                                                        $scope.$root.showAlert($filter('translate')('A02.suggest_list.alert2'));
                                                                        },
                                                                        //按下右上角X後會呼叫此function
                                                                        function (dialog) {
                                                                                angular.element(target).removeClass('is-focus');
                                                                                dialog.hide();
                                                                        },
                                                                        {
                                                                                defaultNum: item.sug_qty,
                                                                                decimal: false
                                                                        });
                                                        },
                                                        back: function () {
                                                                dialog.hide();
                                                        },
                                                        submit_action: function (request) {
                                                                $MMWService.sendToServer({
                                                                        uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_process',
                                                                        content: request,
                                                                        success: function (data) {
                                                                                if (data.dispatch_msg && data.dispatch_msg.length > 0) {
                                                                                        var msg = data.dispatch_msg.join("<br>")
                                                                                        $scope.$root.showConfirm(msg, function (confirm_dialog) {
                                                                                                confirm_dialog.hide();
                                                                                                enforce_dispatch_action(request, function () {
                                                                                                        search({ return_type: '0120' }, function () {
                                                                                                                var str_array = [];
                                                                                                                for (var i in request.dispatch_to) {
                                                                                                                        var str = request.need_dispatch_plot_detail.length +
                                                                                                                                $filter('translate')('A02.msg.sendWorkSuccess') + '[' + request.dispatch_to[i].machine_no + ']'
                                                                                                                        str_array.push(str);
                                                                                                                }
                                                                                                                $scope.$root.showToast(str_array.join("<br>"));
                                                                                                                $scope.Mode = '';
                                                                                                                $scope.select_all_bool = false;
                                                                                                                $scope.selectRollback = 0;
                                                                                                                if ($scope.selectMachine)
                                                                                                                        $scope.selectMachine.dispatch_size = 0;
                                                                                                        });
                                                                                                });
                                                                                        });
                                                                                }
                                                                                else {
                                                                                        search({ return_type: '0120' }, function () {
                                                                                                var str_array = [];
                                                                                                for (var i in request.dispatch_to) {
                                                                                                        var str = request.need_dispatch_plot_detail.length +
                                                                                                                $filter('translate')('A02.msg.sendWorkSuccess') + '[' + request.dispatch_to[i].machine_no + ']'
                                                                                                        str_array.push(str);
                                                                                                }
                                                                                                $scope.$root.showToast(str_array.join("<br>"));
                                                                                                $scope.showMode = 'query';
                                                                                                $scope.Mode = '';
                                                                                                $scope.select_all_bool = false;
                                                                                                $scope.selectRollback = 0;
                                                                                                if ($scope.selectMachine)
                                                                                                        $scope.selectMachine.dispatch_size = 0;
                                                                                        });
                                                                                }
                                                                        }
                                                                });
                                                        },
                                                        normal_confirm: function () {

                                                                dialog.submit_action(dialog.submit_data);
                                                                dialog.hide();
                                                        },
                                                        suggest_confirm: function () {
                                                                var check_length = 0;
                                                                if (work_mode == 0) {
                                                                        for (var i in dialog.suggest_detail) {
                                                                                var op_no = dialog.suggest_detail[i].op_no;
                                                                                var lot_no = dialog.suggest_detail[i].lot_no;
                                                                                var sug_qty = dialog.suggest_detail[i].sug_qty;
                                                                                for (var j in dialog.submit_data.need_dispatch_plot_detail) {
                                                                                        var org_op_no = dialog.submit_data.need_dispatch_plot_detail[j].op_no;
                                                                                        var org_lot_no = dialog.submit_data.need_dispatch_plot_detail[j].plot_no;
                                                                                        if (org_op_no == op_no && org_lot_no == lot_no)
                                                                                                dialog.submit_data.need_dispatch_plot_detail[j].qty = sug_qty;
                                                                                }
                                                                        }
                                                                        dialog.submit_data.need_dispatch_plot_detail =
                                                                                dialog.submit_data.need_dispatch_plot_detail.filter(function (item) {
                                                                                        if (item.qty > 0)
                                                                                                return item;
                                                                                });
                                                                        check_length = dialog.submit_data.need_dispatch_plot_detail.length;
                                                                        if (dialog.submit_data.need_dispatch_plot_detail.length == 1) {
                                                                                if (dialog.submit_data.dispatch_to && dialog.submit_data.dispatch_to.length == 1) {
                                                                                        dialog.submit_data.dispatch_to[0].qty = dialog.submit_data.need_dispatch_plot_detail[0].qty;
                                                                                }
                                                                        }
                                                                }
                                                                else if (work_mode == 1) {
                                                                        for (var i in dialog.suggest_detail) {
                                                                                var equipment_no = dialog.suggest_detail[i].equipment_no;
                                                                                var sug_qty = dialog.suggest_detail[i].sug_qty;
                                                                                for (var j in dialog.submit_data.dispatch_to) {
                                                                                        var org_equipment_no = dialog.submit_data.dispatch_to[j].machine_no;
                                                                                        if (equipment_no == org_equipment_no)
                                                                                                dialog.submit_data.dispatch_to[j].qty = sug_qty;
                                                                                }
                                                                        }
                                                                        dialog.submit_data.dispatch_to =
                                                                                dialog.submit_data.dispatch_to.filter(function (item) {
                                                                                        if (item.qty > 0)
                                                                                                return item;
                                                                                });
                                                                        check_length = dialog.submit_data.dispatch_to.length;
                                                                }
                                                                if (check_length > 0)
                                                                        dialog.submit_action(dialog.submit_data);
                                                                else {
                                                                        search({ return_type: '0120' }, function () {
                                                                                $scope.$root.showAlert($filter('translate')('A02.suggest_list.alert1'));
                                                                                $scope.showMode = 'query';
                                                                                $scope.Mode = '';
                                                                                $scope.select_all_bool = false;
                                                                                $scope.selectRollback = 0;
                                                                                if ($scope.selectMachine)
                                                                                        $scope.selectMachine.dispatch_size = 0;
                                                                        });
                                                                }
                                                                dialog.hide();
                                                        }
                                                }
                                        }
                                );
                        }
                        $scope.mwlightColor = function (states) {
                                var lightColor;
                                if (states == '0') {
                                        lightColor = 'light-white';
                                } else if (states == '1') {
                                        lightColor = 'light-green';
                                } if (states == '2') {
                                        lightColor = 'light-blue';
                                }
                                return lightColor;
                        };

                        $scope.mlightColor = function (states) {
                                var lightColor;
                                if (states == 'H') {
                                        lightColor = 'red';
                                } else if (states == 'M') {
                                        lightColor = 'yellow';
                                } if (states == 'L') {
                                        lightColor = 'green';
                                }
                                return lightColor;
                        };

                        $scope.confirmEditSeq = function () {
                                var content = {
                                        machine_no: $scope.selectMachine.machine_no,
                                        dispatch_plot_detail: []
                                };
                                $scope.dispatched_detail.forEach(function (detail, index) {
                                        content.dispatch_plot_detail.push({
                                                plot_no: detail.plot_no,
                                                op_no: detail.op_no,
                                                seq: index
                                        });
                                        detail.seq = index;
                                });
                                $MMWService.sendToServer({
                                        uri: 'ServicesSTD.Module_WIP.change_dispatch_seq_process',
                                        content: content,
                                        success: function (data) {
                                                $scope.$root.showToast($filter('translate')('A02.msg.seqChangeSuccess'));
                                                $scope.Mode = 'MachineExpend';
                                                initMachineExpend($scope.selectMachine);
                                        }
                                });
                        };

                        $scope.cancelEditSeq = function () {
                                $scope.Mode = 'MachineExpend';
                                $scope.dispatched_detail = dispatched_detail_backup.slice();
                                dis_date_separate_action();
                        };

                        $scope.selectRollback = 0;
                        //$scope.detailRollback = function (index, detail) {
                        //        if (detail.status == '0') {
                        //                // 此任務在智派工納入派工，不可重複勾選！
                        //                return $scope.$root.showAlert($filter('translate')('A02.msg.sjds_dispatch_can_not_select'));
                        //        }
                        //        if ($scope.Mode != 'EditSeq') {
                        //                if (detail.checked == 'Y') {
                        //                        detail.checked = undefined;
                        //                        $scope.selectRollback--;
                        //                } else if (!detail.checked) {
                        //                        detail.checked = 'Y';
                        //                        $scope.selectRollback++;
                        //                }
                        //                if ($scope.selectRollback == 0) {
                        //                        $scope.Mode = 'MachineExpend';
                        //                } else {
                        //                        $scope.Mode = 'Rollback';
                        //                }
                        //        }
                        //};
                        $scope.detailRollbackAll = function () {
                                if ($scope.dispatched_detail.length <= 0)
                                        return;
                                for (var i in $scope.dispatched_detail) {
                                        if ($scope.roll_back_all_bool)
                                                $scope.dispatched_detail[i].checked = '';
                                        else {
                                                // 狀態 0 代表任務在智派工納入派工，不可勾選！
                                                if ($scope.dispatched_detail[i].status == '0')
                                                        $scope.dispatched_detail[i].checked = '';
                                                else
                                                        $scope.dispatched_detail[i].checked = 'N';
                                        }
                                }
                                if ($scope.roll_back_all_bool) {
                                        $scope.roll_back_all_bool = false;
                                        $scope.selectRollback = 0;
                                        $scope.Mode = 'MachineExpend';
                                }
                                else {
                                        $scope.roll_back_all_bool = true;
                                        $scope.Mode = 'Rollback';
                                        $scope.selectRollback = $scope.dispatched_detail.length;
                                }
                        },


                        $scope.getPlotNoStatas = function () {
                                $scope.$root.showSelect({
                                        label: "label",
                                        code: 'code',
                                        selectCode: $scope.project_status_code,
                                        list: $scope.data,
                                        confirm: function (item, select_dialog) {
                                                select_dialog.hide();
                                                if ($scope.project_status_code != item.code)
                                                        $scope.equipment_sort_mode_change = true;
                                                else
                                                        $scope.equipment_sort_mode_change = false;
                                                $scope.project_status_code = item.code;
                                                $scope.initPlotNoStatus = item.label;
                                                // 保存生产批状态
                                                localStorage.setItem($scope.selectareaNo,JSON.stringify({code: $scope.project_status_code,label:$scope.initPlotNoStatus}));
                                                // 先查op_list 再查 undispatched_list跟machine_statistcs_list
                                                search({ return_type: '1000' }, function () {
                                                        search({ return_type: '0120' });
                                                });
                                        }
                                });
                        }
                        //設備排序 select 開窗
                        $scope.getEquipmentSortModeList = function () {
                                $scope.$root.showSelect({
                                        label: "label",
                                        code: 'code',
                                        selectCode: $scope.equipment_sort_mode,
                                        list: $scope.equipment_sort_option_list,
                                        confirm: function (item, select_dialog) {
                                                select_dialog.hide();
                                                if ($scope.equipment_sort_mode != item.code)
                                                        $scope.equipment_sort_mode_change = true;
                                                else
                                                        $scope.equipment_sort_mode_change = false;
                                                $scope.equipment_sort_mode = item.code;
                                                $scope.equipment_sort_mode_label = item.label;
                                                EquipmentSortAction();
                                        }
                                });
                        }
                        function EquipmentSortAction() {
                                //模式改變 dis order score 歸零
                                if ($scope.equipment_sort_mode_change) {
                                        for (var i in $scope.machine_detail)
                                                $scope.machine_detail[i].dis_order_score = 0
                                }
                                switch ($scope.equipment_sort_mode) {
                                        // 20211125 modify by Alan for #0103170: [sMES]派工作業設備順序顛倒[宏毅]
                                        // 修正標準預設排序(case: 0,5,6,7)
                                        case "0":
                                                $scope.machine_detail = $filter('orderBy')($scope.machine_detail, ['machine_no']);
                                                break;
                                        case "1":
                                                $scope.machine_detail = $filter('orderBy')($scope.machine_detail, ['times', 'machine_no'], true);
                                                break;
                                        case "2":
                                                $scope.machine_detail = $filter('orderBy')($scope.machine_detail, ['good_rate', 'machine_no'], true);
                                                break;
                                        case "3":
                                                $scope.machine_detail = $filter('orderBy')($scope.machine_detail, ['used_load', 'machine_no'], true);
                                                break;
                                        case "4":
                                                $scope.machine_detail = $filter('orderBy')($scope.machine_detail, ['used_load', 'machine_no']);
                                                break;
                                        case "5":
                                                var dis_data = $filter('filter')($scope.dispatch_detail, { checked: "Y" });
                                                var has_score = false;
                                                dis_data.forEach(function (item) {
                                                        var condition = { op_no: item.op_no, product_no: item.item_no, product_ver: item.item_version };
                                                        var equipment_data = $filter('filter')($scope.product_detail, condition);
                                                        equipment_data.forEach(function (eq_item) {
                                                                $scope.machine_detail.forEach(function (m_item) {
                                                                        if (m_item.machine_no == eq_item.equipment_no)
                                                                                m_item.dis_order_score += eq_item.times;

                                                                        if (m_item.dis_order_score > 0)
                                                                                has_score = true;
                                                                });
                                                        });

                                                });
                                                if ($scope.Mode != "EditSendWork")
                                                        $scope.$root.showAlert($filter('translate')('A02.equipment_sort_list.alert_1'));
                                                $scope.machine_detail = has_score
                                                        ? $filter('orderBy')($scope.machine_detail, ['dis_order_score', 'machine_no'], true)
                                                        : $filter('orderBy')($scope.machine_detail, ['machine_no']);
                                                break;
                                        case "6":
                                                var dis_data = $filter('filter')($scope.dispatch_detail, { checked: "Y" });
                                                var has_score = false;
                                                dis_data.forEach(function (item) {
                                                        var condition = { op_no: item.op_no, product_no: item.item_no, product_ver: item.item_version };
                                                        var equipment_data = $filter('filter')($scope.product_detail, condition);
                                                        equipment_data.forEach(function (eq_item) {
                                                                $scope.machine_detail.forEach(function (m_item) {
                                                                        if (m_item.machine_no == eq_item.equipment_no)
                                                                                m_item.dis_order_score += eq_item.good_rate;
                                                                        if (m_item.dis_order_score > 0)
                                                                                has_score = true;
                                                                });
                                                        });
                                                });
                                                if ($scope.Mode != "EditSendWork")
                                                        $scope.$root.showAlert($filter('translate')('A02.equipment_sort_list.alert_1'));
                                                $scope.machine_detail = has_score
                                                        ? $filter('orderBy')($scope.machine_detail, ['dis_order_score', 'machine_no'], true)
                                                        : $filter('orderBy')($scope.machine_detail, ['machine_no']);
                                                break;
                                        case "7":
                                                var dis_data = $filter('filter')($scope.dispatch_detail, { checked: "Y" });
                                                var has_score = false;
                                                dis_data.forEach(function (item) {
                                                        var condition = { op_no: item.op_no, product_no: item.item_no, product_ver: item.item_version };
                                                        var equipment_data = $filter('filter')($scope.product_detail, condition);
                                                        equipment_data.forEach(function (eq_item) {
                                                                $scope.machine_detail.forEach(function (m_item) {
                                                                        if (m_item.machine_no == eq_item.equipment_no)
                                                                                m_item.dis_order_score += eq_item.equipment_seq;
                                                                        if (m_item.dis_order_score > 0)
                                                                                has_score = true;
                                                                });
                                                        });
                                                });
                                                if ($scope.Mode != "EditSendWork")
                                                        $scope.$root.showAlert($filter('translate')('A02.equipment_sort_list.alert_1'));
                                                $scope.machine_detail = has_score
                                                        ? $filter('orderBy')($scope.machine_detail, ['dis_order_score', 'machine_no'])
                                                        : $filter('orderBy')($scope.machine_detail, ['machine_no']);
                                                break;
                                }
                                //console.log($scope.machine_detail);
                        }
                        //設備排序動作(改派 與 分量派)
                        function EquipmentSortForDialogAction(dis_item, machine_data) {
                                //init score for sort
                                for (var i in machine_data)
                                        machine_data[i].dis_order_score = 0
                                //console.log(data);
                                if (typeof dis_item === "undefined")
                                        return;
                                if (typeof machine_data === "undefined" || machine_data.length <= 0)
                                        return;

                                switch ($scope.equipment_sort_mode) {
                                        // 20211125 modify by Alan for #0103170: [sMES]派工作業設備順序顛倒[宏毅]
                                        // 修正標準預設排序(case: 0,5,6,7)
                                        case "0":
                                                machine_data = $filter('orderBy')(machine_data, ['machine_no']);
                                                break;
                                        case "1":
                                                machine_data = $filter('orderBy')(machine_data, ['times', 'machine_no'], true);
                                                break;
                                        case "2":
                                                machine_data = $filter('orderBy')(machine_data, ['good_rate', 'machine_no'], true);
                                                break;
                                        case "3":
                                                machine_data = $filter('orderBy')(machine_data, ['used_load', 'machine_no'], true);
                                                break;
                                        case "4":
                                                machine_data = $filter('orderBy')(machine_data, ['used_load', 'machine_no']);
                                                break;
                                        case "5":
                                                var dis_data = [dis_item];
                                                var has_score = false;
                                                dis_data.forEach(function (item) {
                                                        var condition = { op_no: item.op_no, product_no: item.item_no, product_ver: item.item_version };
                                                        var equipment_data = $filter('filter')($scope.product_detail, condition);
                                                        equipment_data.forEach(function (eq_item) {
                                                                machine_data.forEach(function (m_item) {
                                                                        if (m_item.machine_no == eq_item.equipment_no)
                                                                                m_item.dis_order_score += eq_item.times;

                                                                        if (m_item.dis_order_score > 0)
                                                                                has_score = true;
                                                                });
                                                        });

                                                });
                                                machine_data = has_score
                                                        ? $filter('orderBy')(machine_data, ['dis_order_score', 'machine_no'], true)
                                                        : $filter('orderBy')(machine_data, ['machine_no']);
                                                break;
                                        case "6":
                                                var dis_data = [dis_item];
                                                var has_score = false;
                                                dis_data.forEach(function (item) {
                                                        var condition = { op_no: item.op_no, product_no: item.item_no, product_ver: item.item_version };
                                                        var equipment_data = $filter('filter')($scope.product_detail, condition);
                                                        equipment_data.forEach(function (eq_item) {
                                                                machine_data.forEach(function (m_item) {
                                                                        if (m_item.machine_no == eq_item.equipment_no)
                                                                                m_item.dis_order_score += eq_item.good_rate;
                                                                        if (m_item.dis_order_score > 0)
                                                                                has_score = true;
                                                                });
                                                        });
                                                });
                                                machine_data = has_score
                                                        ? $filter('orderBy')(machine_data, ['dis_order_score', 'machine_no'], true)
                                                        : $filter('orderBy')(machine_data, ['machine_no']);
                                                break;
                                        case "7":
                                                var dis_data = [dis_item];
                                                var has_score = false;
                                                dis_data.forEach(function (item) {
                                                        var condition = { op_no: item.op_no, product_no: item.item_no, product_ver: item.item_version };
                                                        var equipment_data = $filter('filter')($scope.product_detail, condition);
                                                        equipment_data.forEach(function (eq_item) {
                                                                machine_data.forEach(function (m_item) {
                                                                        if (m_item.machine_no == eq_item.equipment_no)
                                                                                m_item.dis_order_score += eq_item.equipment_seq;
                                                                        if (m_item.dis_order_score > 0)
                                                                                has_score = true;
                                                                });
                                                        });
                                                });
                                                machine_data = has_score
                                                        ? $filter('orderBy')(machine_data, ['dis_order_score', 'machine_no'])
                                                        : $filter('orderBy')(machine_data, ['machine_no']);
                                                break;
                                }
                                return machine_data;
                        }
                        //撤回
                        $scope.confirmRollback = function () {
                                $mdDialog.dialog('module/moduleA/program/A02/A02_withdraw_menu.html', withdraw_dialog_controller);
                        };
                        //撤回開窗 controller
                        function withdraw_dialog_controller(dialog) {
                                var controller =
                                {
                                        content: {},
                                        select_list: [],
                                        show_data: [],
                                        select_label: "",
                                        select_machine_no: $scope.selectMachine.machine_no,
                                        isRunning: false,
                                        init: function () {
                                                dialog.select_list = [
                                                        { "label": $filter('translate')('A02.with_draw.list_label_0'), "code": "0" },
                                                        { "label": $filter('translate')('A02.with_draw.list_label_1'), "code": "1" },
                                                        { "label": $filter('translate')('A02.with_draw.list_label_2'), "code": "2" },
                                                        { "label": $filter('translate')('A02.with_draw.list_label_3'), "code": "3" }];
                                                dialog.content =
                                                {
                                                        need_dispatch_plot_detail: [],
                                                        dispatch_to: [],
                                                        work_mode: 0,
                                                        with_draw_mode: dialog.select_list[0].code,
                                                        dispatch_day: moment($scope.work_date).format('YYYY-MM-DD')
                                                };
                                                dialog.show_data = [];
                                                dialog.isRunning = false;
                                                $scope.dispatched_detail.forEach(function (detail) {
                                                        if (detail.checked == 'Y') {
                                                                if (detail.states != '0') {
                                                                        dialog.isRunning = true;
                                                                }
                                                                dialog.show_data.push({
                                                                        plot_no: detail.plot_no,
                                                                        op_name: detail.op_name,
                                                                        op_no: detail.op_no,
                                                                        limit_qty: detail.plot_qty,
                                                                        qty: detail.plot_qty,
                                                                        mo_no: detail.wo_no,
                                                                        uncheck_in_qty: detail.uncheck_in_qty,
                                                                        item_no: detail.item_no,
                                                                        item_name: detail.item_name,
                                                                        item_version: detail.item_version,
                                                                        item_spec: detail.item_spec,
                                                                        mo_no: detail.wo_no,
                                                                        machine_no: $scope.selectMachine.machine_no,
                                                                        plot_start_time: detail.plot_start_time,
                                                                        plot_end_time: detail.plot_end_time
                                                                });
                                                        }
                                                });
                                                dialog.select_label = dialog.select_list[0].label;
                                        },
                                        load_withdraw_list: function () {
                                                $scope.$root.showSelect({
                                                        label: "label",
                                                        code: 'code',
                                                        selectCode: dialog.select_code,
                                                        list: dialog.select_list,
                                                        confirm: function (item, select_dialog) {
                                                                if (dialog.content.with_draw_mode != item.code) {
                                                                        //mode change init dialog display qty
                                                                        dialog.show_data.forEach(function (item) {
                                                                                item.qty = item.limit_qty;
                                                                        });
                                                                }
                                                                select_dialog.hide();
                                                                dialog.select_label = item.label;
                                                                dialog.content.with_draw_mode = item.code;
                                                        }
                                                });
                                        },
                                        checkWithdrawQty: function (event, item) {
                                                var target = event.currentTarget;
                                                angular.element(target).addClass('is-focus');
                                                $calculater.open(function (num, dialog) {
                                                        angular.element(target).removeClass('is-focus');
                                                        dialog.hide();
                                                        if (num > 0 && num <= item.limit_qty)
                                                                item.qty = num;
                                                        else
                                                                $scope.$root.showAlert($filter('translate')('A02.alert.msg1'));
                                                },
                                                        //按下右上角X後會呼叫此function
                                                        function (dialog) {
                                                                angular.element(target).removeClass('is-focus');
                                                                dialog.hide();
                                                        },
                                                        {
                                                                defaultNum: item.qty,
                                                                decimal: false
                                                        });
                                        },
                                        back: function () {
                                                dialog.hide();
                                        },
                                        confirm: function () {
                                                //20220728 modify by wangzy for 0116240: 派工撤回报错
                                                //for循环取值不对，应该取length才对，导致赋值need_dispatch_plot_detail异常
                                                for (var i = 0; i < dialog.show_data.length; i++) {
                                                        dialog.content.need_dispatch_plot_detail.push({
                                                                plot_no: dialog.show_data[i].plot_no,
                                                                op_no: dialog.show_data[i].op_no,
                                                                qty: dialog.show_data[i].qty,
                                                                mo_no: dialog.show_data[i].mo_no,
                                                                machine_no: dialog.show_data[i].machine_no,
                                                                plot_start_time: dialog.show_data[i].plot_start_time,
                                                                plot_end_time: dialog.show_data[i].plot_end_time
                                                        });
                                                }
                                                var _fn = function () {
                                                        $MMWService.sendToServer({
                                                                uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_process',
                                                                content: dialog.content,
                                                                success: function (data) {
                                                                        if (data.dispatch_msg && data.dispatch_msg.length > 0) {
                                                                                var msg = data.dispatch_msg.join("<br>")
                                                                                $scope.$root.showConfirm(msg, function (confirm_dialog) {
                                                                                        confirm_dialog.hide();
                                                                                        enforce_dispatch_action(request, function () {
                                                                                                search({ return_type: '0110' }, function () {
                                                                                                        $scope.$root.showToast(
                                                                                                                $filter('translate')('A02.msg.rollbackSuccess.1')
                                                                                                                + $scope.selectRollback
                                                                                                                + $filter('translate')('A02.msg.rollbackSuccess.2')
                                                                                                        );
                                                                                                        $scope.Mode = 'MachineExpend';
                                                                                                        $scope.selectRollback = 0;
                                                                                                        $scope.roll_back_all_bool = false;
                                                                                                        $scope.selectMachine.dispatch_size = 0;
                                                                                                        var machine = $filter('filter')($scope.machine_detail, { machine_no: $scope.selectMachine.machine_no });
                                                                                                        if (machine != undefined && machine.length > 0) {
                                                                                                                $scope.selectMachine = machine[0];
                                                                                                        }
                                                                                                        initMachineExpend($scope.selectMachine);
                                                                                                });
                                                                                        });
                                                                                });
                                                                        }
                                                                        else {
                                                                                search({ return_type: '0110' }, function () {
                                                                                        $scope.$root.showToast(
                                                                                                $filter('translate')('A02.msg.rollbackSuccess.1')
                                                                                                + $scope.selectRollback
                                                                                                + $filter('translate')('A02.msg.rollbackSuccess.2')
                                                                                        );
                                                                                        $scope.Mode = 'MachineExpend';
                                                                                        $scope.selectRollback = 0;
                                                                                        $scope.roll_back_all_bool = false;
                                                                                        $scope.selectMachine.dispatch_size = 0;
                                                                                        var machine = $filter('filter')($scope.machine_detail, { machine_no: $scope.selectMachine.machine_no });
                                                                                        if (machine != undefined && machine.length > 0) {
                                                                                                $scope.selectMachine = machine[0];
                                                                                        }
                                                                                        initMachineExpend($scope.selectMachine);
                                                                                });
                                                                        }
                                                                }
                                                        });
                                                };
                                                if (dialog.isRunning) {
                                                        $scope.$root.showConfirm($filter('translate')('A02.msg.plot_still_running'), function (confirm_dialog) {
                                                                confirm_dialog.hide();
                                                                dispatch_info_calculation_process(dialog.content, function (data) {
                                                                        if (data && data.msg != '') {
                                                                                $scope.$root.showConfirm(data.msg, function (dialogType) {
                                                                                        dialogType.hide();
                                                                                        _fn();
                                                                                });
                                                                        }
                                                                        else {
                                                                                _fn();
                                                                        };
                                                                });
                                                        });
                                                }
                                                else {
                                                        _fn();
                                                }
                                                dialog.hide();
                                        }
                                };
                                return controller;
                        };
                        //取消撤回/移轉
                        $scope.cancelRollback = function () {
                                $scope.dispatched_detail.forEach(function (detail) {
                                        detail.checked = undefined;
                                });
                                $scope.selectRollback = 0;
                                $scope.Mode = 'MachineExpend';
                                $scope.roll_back_all_bool = false;
                        };

                        //改派
                        $scope.confirmTransfer = function () {
                                var transferItem,
                                        feedback = function (data) {
                                                dispatchItem = transferItem;
                                                MachineListMode = '2';//轉移
                                                machineList = EquipmentSortForDialogAction(dispatchItem, data);
                                                $mdDialog.dialog(
                                                        'module/moduleA/program/A02/A2_MachineList.tmp.html',
                                                        MachineListController
                                                );
                                        };
                                // 取出勾選的已派生產批
                                $scope.dispatched_detail.forEach(function (detail) {
                                        if (detail.checked == 'Y') {
                                                transferItem = detail;
                                                transferItem.qty = detail.plot_qty;
                                                transferItem.machine_no = $scope.selectMachine.machine_no;
                                        }
                                });
                                if (transferItem) {
                                        if ($scope.isLine == '1')
                                                getLineMachineList(transferItem.plot_no, transferItem.op_no, $scope.work_date, feedback);
                                        else
                                                getMachineList($scope.work_date, feedback);
                                }
                        };

                        // 批次合併
                        $scope.confirmBatchMerge = function () {
                                $mdDialog.dialog(
                                        'module/moduleA/program/A02/A02_batchMerge.tmp.html', function (dialog) {
                                                return {
                                                        batchMerge_input: '',
                                                        back: function () {
                                                                dialog.hide();
                                                        },
                                                        confirm: function () {
                                                                var content = {
                                                                        work_mode: 3,
                                                                        dispatch_day: moment($scope.work_date).format('YYYY-MM-DD'),
                                                                        machine_detail: [{
                                                                                machine_no: $scope.selectMachine.machine_no,
                                                                                dispatched_detail: []
                                                                        }],
                                                                        need_dispatch_plot_detail: []
                                                                };

                                                                $scope.dispatched_detail.forEach(function (item) {
                                                                        if (item.checked == 'Y') {
                                                                                item.qty = (+item.plot_qty);
                                                                                item.batch_mark = dialog.batchMerge_input;
                                                                                content.machine_detail[0].dispatched_detail.push(item);
                                                                                content.need_dispatch_plot_detail.push(item);
                                                                        }
                                                                });

                                                                $MMWService.sendToServer({
                                                                        uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_process',
                                                                        content: content,
                                                                        success: function (data) {
                                                                                if (data.dispatch_msg && data.dispatch_msg.length > 0) {
                                                                                        var msg = data.dispatch_msg.join("<br>")
                                                                                        $scope.$root.showConfirm(msg, function (confirm_dialog) {
                                                                                                confirm_dialog.hide();
                                                                                                enforce_dispatch_action(request, function () {
                                                                                                        dialog.hide();
                                                                                                        dialog.batchMerge_input = '';
                                                                                                });
                                                                                        });
                                                                                }
                                                                                else {
                                                                                        dialog.hide();
                                                                                        dialog.batchMerge_input = '';
                                                                                }

                                                                        }
                                                                });
                                                        }
                                                }
                                        }
                                )
                        };

                        // 刪除批次合併註記
                        $scope.deleteBatchMergeMark = function (detail) {
                                detail.batch_mark = '';
                                var content = {
                                        work_mode: 3,
                                        dispatch_day: moment($scope.work_date).format('YYYY-MM-DD'),
                                        machine_detail: [{
                                                machine_no: $scope.selectMachine.machine_no,
                                                dispatched_detail: [detail]
                                        }],
                                        need_dispatch_plot_detail: [detail]
                                };
                                $MMWService.sendToServer({
                                        uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_process',
                                        content: content,
                                        success: function (data, response) {
                                                if (response.isSuccess) {
                                                        // 批次合併註記刪除成功
                                                        $scope.$root.showToast($filter('translate')('A02.msg.batchMerge_delete_success'));
                                                }
                                        }
                                });
                        };

                        function MachineListConfirmTransfer(dialog) {
                                var dispatchSum = 0;
                                var content = {
                                        need_dispatch_plot_detail: [dispatchItem],
                                        dispatch_to: [],
                                        work_mode: 2,
                                        transfer_day: moment(dialog.work_date).format('YYYY-MM-DD'),//要轉移的目標日期
                                        dispatch_day: moment($scope.work_date).format('YYYY-MM-DD')//派工當時的日期
                                };
                                dialog.machineList.forEach(function (machine, index) {
                                        if (machine.inputQty != undefined && machine.inputQty != 0) {
                                                content.dispatch_to.push({ machine_no: machine.machine_no, qty: machine.inputQty });
                                                dispatchSum += (+machine.inputQty);
                                        }
                                });

                                var _fn = function (request) {
                                        $MMWService.sendToServer({
                                                uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_process',
                                                content: request,
                                                success: function (data) {
                                                        //改派以後不會跳日
                                                        //$scope.work_date = dialog.work_date;
                                                        if (data.dispatch_msg && data.dispatch_msg.length > 0) {
                                                                var msg = data.dispatch_msg.join("<br>")
                                                                $scope.$root.showConfirm(msg, function (confirm_dialog) {
                                                                        confirm_dialog.hide();
                                                                        enforce_dispatch_action(request, function () {
                                                                                dialog.hide();
                                                                                search({ return_type: '0110' }, function () {
                                                                                        $scope.$root.showToast(dispatchItem.plot_no + $filter('translate')('A02.msg.transSuccess'));
                                                                                        $scope.Mode = 'MachineExpend';
                                                                                        $scope.selectRollback = 0;
                                                                                        $scope.selectMachine.dispatch_size = 0;
                                                                                        var machine = $filter('filter')($scope.machine_detail, { machine_no: $scope.selectMachine.machine_no });
                                                                                        if (machine != undefined && machine.length > 0) {
                                                                                                $scope.selectMachine = machine[0];
                                                                                        }
                                                                                        initMachineExpend($scope.selectMachine);
                                                                                });
                                                                        });
                                                                });
                                                        }
                                                        else {
                                                                dialog.hide();
                                                                search({ return_type: '0110' }, function () {
                                                                        $scope.$root.showToast(dispatchItem.plot_no + $filter('translate')('A02.msg.transSuccess'));
                                                                        $scope.Mode = 'MachineExpend';
                                                                        $scope.selectRollback = 0;
                                                                        $scope.selectMachine.dispatch_size = 0;
                                                                        var machine = $filter('filter')($scope.machine_detail, { machine_no: $scope.selectMachine.machine_no });
                                                                        if (machine != undefined && machine.length > 0) {
                                                                                $scope.selectMachine = machine[0];
                                                                        }
                                                                        initMachineExpend($scope.selectMachine);
                                                                });
                                                        }
                                                }
                                              
                                        });
                                };

                                if (content.dispatch_to.length == 0) {
                                        //尚未輸入派工數量
                                        $scope.$root.showAlert($filter('translate')('A02.msg.no_dispatch_qty'));
                                } else if (dispatchSum <= dispatchItem.qty) {
                                        dispatch_info_calculation_process(content, function (data) {
                                                if (data && data.suggest_detail && data.suggest_detail.length > 0) {
                                                        OpenMachineSuggestListDialog(1, content, data.suggest_detail);
                                                        dialog.hide();
                                                }
                                                else if (data && data.msg != '') {
                                                        $scope.$root.showConfirm(data.msg, function (dialogType) {
                                                                dialogType.hide();
                                                                _fn(content);
                                                        });
                                                }
                                                else {
                                                        _fn(content);
                                                };
                                        });
                                } else {
                                        $scope.$root.showAlert($filter('translate')('A02.msg.transOver') + dispatchItem.qty);
                                }
                        }

                        $scope.dispatchedFilter = function (item) {
                                return item.states != '0';
                        };

                        function dispatch_info_calculation_process(content, callback) {
                                $MMWService.sendToServer({
                                        uri: 'ServicesSTD.Module_WIP.dispatch_info_calculation_process',
                                        content: content,
                                        success: function (data) {
                                                if (callback)
                                                        callback(data);
                                        }
                                });
                        };

                        // 分頁
                        $scope.getPages = function (list, PageConfig,filterItem) {
                                if (list) {
                                        if ($scope.order_by_mode.name != "")
                                                list = $filter('orderBy')(list, $scope.order_by_mode.name, $scope.order_by_mode.sort);
                                        var temp_list = list.filter(function (item, index, array) {
                                                var isOK = true,
                                                        keys = Object.keys(filterItem);
                                                for (var i = 0; i < keys.length; i++) {
                                                        var key = keys[i];
                                                        if (isOK && item[key] != null && filterItem[key] && filterItem[key] != '') {
                                                                if (item[key].toString().indexOf(filterItem[key]) == -1) {
                                                                        isOK = false;
                                                                        break;
                                                                }
                                                        }
                                                }
                                                return isOK;
                                        });
                                        if (PageConfig) {
                                                if (temp_list.length != 0) {
                                                        PageConfig.total_page = Math.ceil(temp_list.length / PageConfig.page_count);

                                                        if (PageConfig.page >= PageConfig.total_page) {
                                                                PageConfig.page = 0;
                                                        }
                                                        var index = PageConfig.page * PageConfig.page_count;
                                                        return temp_list.slice(index, index + PageConfig.page_count);
                                                } else {
                                                        PageConfig.total_page = 1;
                                                        PageConfig.page = 0;
                                                }
                                        } else {
                                                return temp_list;
                                        }
                                } else {

                                        return list;
                                }
                        };
                        function enforce_dispatch_action(request, feedback) {
                                request.enforce_dispatch_msg = "1";
                                $MMWService.sendToServer({
                                        uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_process',
                                        content: request,
                                        success: function (data) {
                                                feedback();
                                        }
                                });
                        }
                        
                        // 20230911 modify by Alan for #136071: 增加跨頁選中功能
                        // 篩選時，清空已選中的項目
                        $scope.$watch('dispatch_filter', (newVal, oldVal) => {
                                dispatch_detail_checked = [];
                                $scope.dispatch_detail.forEach((item) => item.checked = 'N');
                                $scope.Mode = '';
                                $scope.select_all_bool = false;
                        }, true);
                }
        ];
});
